Editor

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

quadratic_equation.py
import math
# Each sample is (a, b, c) for a*x^2 + b*x + c = 0, with a not 0
samples = [(1, -5, 6), (1, -4, 4), (1, 2, 5)]
# or: a = float(input("Enter a: ")), and the same for b and c
for a, b, c in samples:
d = b * b - 4 * a * c # the discriminant
print(f"a = {a}, b = {b}, c = {c}, discriminant = {d}")
if d > 0:
root1 = (-b + math.sqrt(d)) / (2 * a)
root2 = (-b - math.sqrt(d)) / (2 * a)
print(" Two real roots:", root1, "and", root2)
elif d == 0:
root = -b / (2 * a)
print(" One repeated real root:", root)
else:
real = -b / (2 * a)
imag = math.sqrt(-d) / (2 * abs(a))
print(f" Two complex roots: {real} + {imag}i and {real} - {imag}i")
Output
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

  1. The discriminant d = b * b - 4 * a * c is worked out first, because its sign decides which case applies.
  2. If d > 0, math.sqrt(d) is a real number and the plus and minus versions of the formula give two different roots.
  3. If d == 0, both versions give the same value, -b / (2 * a), so there is one repeated root.
  4. If d < 0, math.sqrt(d) would raise an error, so the program takes the square root of -d and prints it as the imaginary part, marked with i.

Another way to write it

Using cmath for every case

Using cmath for every case
import cmath
samples = [(1, -5, 6), (1, -4, 4), (1, 2, 5)]
for a, b, c in samples:
d = b * b - 4 * a * c
# cmath.sqrt also works on negative numbers, giving a complex result
root1 = (-b + cmath.sqrt(d)) / (2 * a)
root2 = (-b - cmath.sqrt(d)) / (2 * a)
print(f"a = {a}, b = {b}, c = {c}: roots {root1} and {root2}")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises