My First Python Program: Solutions to Quadratic Equation For Given User Inputs

This was was first python program, from quite a while ago. It was a basic program to learn how conditions, mathematical operators, data types and functions worked in python. Note this can be done almost instantly and more cleanly as follows:

Capture

This is available to view and download from here: https://drive.google.com/open?id=1uxWP8CM5mvlD1Ruy0Dmojar2PTHsBctV

The focus here was to play about with data types, functions and conditions and so on, rather than efficiency, so the following code is more elaborate and excessive.

I first imported the relevant mathematics libraries; cmath and math.

Within the main function, I called for user inputs based on coefficients on their desired equation:

Capture3

We first know there could be a more trivial solution based on these inputs, that is, the case where a=0. I dealt with this linear case first within the main function:

Capture5

Alternatively, where a≠0 we have a quadratic equation. From here, I defined a discriminant function, as for given coefficient inputs, the discriminant will tell us which of the 3 possible solution types our quadratic will take:

  1. Real solutions if the discriminant > 0
  2. Repeat solutions if the discriminant = 0
  3. Complex solutions if the discriminant < 0

caputre6

With this, we have the 3 corresponding sub-conditions within our “else” (the quadratic case), and within this, it is simple to calculate the real root cases using the quadratic equation:

capt

  • Note that in the repeat root case x1=x2, and so from an efficiency perspective (although small an unimportant in this program), just the single root is calculated and printed.

The final case for complex variables requires more thought. Using the function complex(x,y) from cmath we can easily output a complex number, such as complex(1,2)=1+2i. This also could have been done manually by appending the string “i” to the complex variable to avoid using libraries and the annoying output ‘j’ engineers insist upon. Note, we still need to return both conjugate solutions to this equation, that is z=x+yi and z=x-yi. For readability, I defined the ‘real’ and ‘imaginary’ functions to return the desired values ‘x’, ‘y’ by splitting the quadratic equation into its component ‘real’ and ‘imaginary’ parts as follows:

realcomplex

  • Note for im we are square rooting ‘-1 times the discriminant’ in order to return a real coefficient to use for the imaginary part our complex variable.

With each of these, we can insert the correct variable into the ‘complex’ built-in function:

C

  • Note the use of -1*im to return the complex conjugate.

quadraticeqn

The program returns the required solutions.

The program in full is downloadable and viewable here:

https://drive.google.com/open?id=14630cb5ZD2WIj27WOFbSEdKa7htKKo4W