PythonMastery

Solve a quadratic equation in Python

Find the roots of ax² + bx + c = 0 using the discriminant: two real roots, one repeated root, or two complex roots with the cmath module.

The roots of ax² + bx + c = 0 are x = (-b ± √(b² - 4ac)) / 2a. The value under the square root, d = b² - 4ac, is the discriminant. If d is positive there are two real roots, if d is 0 there is one, and if d is negative the roots are complex numbers.

The program

python
import cmath
import math

a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))

if a == 0:
    print("a must not be 0, or the equation is not quadratic.")
else:
    d = b * b - 4 * a * c
    print(f"Discriminant = {d:g}")

    if d > 0:
        root1 = (-b + math.sqrt(d)) / (2 * a)
        root2 = (-b - math.sqrt(d)) / (2 * a)
        print(f"Two real roots: {root1:g} and {root2:g}")
    elif d == 0:
        root = -b / (2 * a)
        print(f"One real root: {root:g}")
    else:
        root1 = (-b + cmath.sqrt(d)) / (2 * a)
        root2 = (-b - cmath.sqrt(d)) / (2 * a)
        print(f"Two complex roots: {root1:g} and {root2:g}")

Typed in this example: 1, -5, 6. Press Run to type your own.

output
a: 1
b: -5
c: 6
Discriminant = 1
Two real roots: 3 and 2

How it works

All three cases

The same steps in a function, tested with one equation of each kind:

python
import cmath
import math


def solve(a, b, c):
    d = b * b - 4 * a * c
    if d > 0:
        return ((-b + math.sqrt(d)) / (2 * a), (-b - math.sqrt(d)) / (2 * a))
    if d == 0:
        return (-b / (2 * a),)
    return ((-b + cmath.sqrt(d)) / (2 * a), (-b - cmath.sqrt(d)) / (2 * a))


print(solve(1, -5, 6))
print(solve(1, -4, 4))
print(solve(1, 2, 5))
output
(3.0, 2.0)
(2.0,)
((-1+2j), (-1-2j))

Python writes the imaginary unit as j, so -1+2j means -1 + 2i. The roots of x² + 2x + 5 = 0 are -1 + 2i and -1 - 2i.

Learn the idea: Control Flow: Conditionals, Numbers in Depth: Integers, Floats, and the math Module