Python Program to Solve a Quadratic Equation
Intermediate · Numbers
A quadratic equation has the form ax² + bx + c = 0, where a is not 0, and its roots come from the formula x = (-b ± √(b² - 4ac)) / 2a. The discriminant d = b² - 4ac decides the kind of roots: two real roots if d is positive, one repeated root if d is 0, and two complex roots if d is negative. This program solves three sample equations, one of each kind.
Program
a = 1, b = -5, c = 6, discriminant = 1 Two real roots: 3.0 and 2.0 a = 1, b = -4, c = 4, discriminant = 0 One repeated real root: 2.0 a = 1, b = 2, c = 5, discriminant = -16 Two complex roots: -1.0 + 2.0i and -1.0 - 2.0i
How it works
- The discriminant
d = b * b - 4 * a * cis worked out first, because its sign decides which case applies. - If
d > 0,math.sqrt(d)is a real number and the plus and minus versions of the formula give two different roots. - If
d == 0, both versions give the same value,-b / (2 * a), so there is one repeated root. - If
d < 0,math.sqrt(d)would raise an error, so the program takes the square root of-dand prints it as the imaginary part, marked with i.
Another way to write it
Using cmath for every case
a = 1, b = -5, c = 6: roots (3+0j) and (2+0j) a = 1, b = -4, c = 4: roots (2+0j) and (2+0j) a = 1, b = 2, c = 5: roots (-1+2j) and (-1-2j)
The cmath module can take the square root of a negative number, so one formula covers all three cases. Python writes the imaginary unit as j, and real roots appear with +0j.
Try it yourself
Add the equation 2x² + 3x - 2 = 0 to samples and check that its roots are 0.5 and -2.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises