Python Quadratic Equation Solver (With Examples)

1 week ago 38
Club.noww.in

For a Python quadratic equation ax² + bx + c = 0, compute the discriminant b² - 4ac and plug it into the quadratic formula. Use cmath.sqrt so negative discriminants give complex roots instead of an error:

import cmath d = cmath.sqrt(b**2 - 4*a*c) roots = ((-b + d) / (2*a), (-b - d) / (2*a))

All roots below were computed on Python 3.12.5 with NumPy 2.5.3, including a program I ran by typing coefficients into the console.

We’ll handle the three discriminant cases, complex roots, NumPy’s roots(), an input program, a projectile word problem, and a numerical trap with very large coefficients.

The quadratic formula in Python

The discriminant tells you how many real roots there are: positive means two, zero means one, negative means none. math.sqrt works only for the first two:

import math def solve_quadratic(a, b, c): d = b * b - 4 * a * c # the discriminant if d > 0: r = math.sqrt(d) return ((-b + r) / (2 * a), (-b - r) / (2 * a)) if d == 0: return (-b / (2 * a),) return () # no real roots for a, b, c in [(1, -5, 6), (1, -4, 4), (1, 2, 5)]: print(f"{a}x^2 {b:+}x {c:+} = 0 -> discriminant {b*b - 4*a*c:>3}, roots {solve_quadratic(a, b, c)}")

Output:

1x^2 -5x +6 = 0 -> discriminant 1, roots (3.0, 2.0) 1x^2 -4x +4 = 0 -> discriminant 0, roots (2.0,) 1x^2 +2x +5 = 0 -> discriminant -16, roots ()
Command Prompt output of a Python quadratic formula function showing two real roots, one repeated root and no real roots by discriminantDiscriminants of 1, 0 and -16 give two roots, one root and no real roots.

math.sqrt on a negative number raises ValueError: math domain error, which is why the function returns an empty tuple instead. See how to import math in Python for more.

Complex roots with cmath

cmath.sqrt handles negative numbers, so one formula covers every case. Real roots come back as complex numbers with a zero imaginary part:

import cmath def solve_any(a, b, c): if a == 0: raise ValueError("a can't be 0; that's a linear equation") d = cmath.sqrt(b * b - 4 * a * c) # works for negative discriminants too return (-b + d) / (2 * a), (-b - d) / (2 * a) print(solve_any(1, 2, 5)) # complex pair print(solve_any(1, -5, 6)) # real roots come back as complex with 0j r1, r2 = solve_any(1, 2, 5) print(f"{r1.real:g} + {r1.imag:g}i and {r2.real:g} {r2.imag:+g}i") try: solve_any(0, 2, 5) except ValueError as err: print("ValueError:", err)

Output:

((-1+2j), (-1-2j)) ((3+0j), (2+0j)) -1 + 2i and -1 -2i ValueError: a can't be 0; that's a linear equation
Command Prompt output of a Python quadratic solver using cmath returning complex roots, real roots as complex, and a ValueError when a is 0x² + 2x + 5 = 0 has the roots -1 + 2i and -1 – 2i. Checking a == 0 avoids a ZeroDivisionError.

Solving quadratics with numpy.roots

You pass np.roots() the coefficients, highest power first, and returns every root. It isn’t limited to quadratics:

import numpy as np print(np.roots([1, -5, 6])) # coefficients from the highest power down print(np.roots([1, 2, 5])) # complex roots print(np.roots([2, 0, -8])) print(np.roots([1, -6, 11, -6])) # works for cubics and higher too

Output:

[3. 2.] [-1.+2.j -1.-2.j] [-2. 2.] [3. 2. 1.]

NumPy finds roots numerically, so you may see tiny rounding differences. For exact symbolic answers, a library like SymPy is the tool.

A quadratic equation program with user input

Here’s a complete program that asks for a, b and c and prints the roots:

import cmath print("Solve ax^2 + bx + c = 0") a = float(input("a: ")) b = float(input("b: ")) c = float(input("c: ")) d = b * b - 4 * a * c root1 = (-b + cmath.sqrt(d)) / (2 * a) root2 = (-b - cmath.sqrt(d)) / (2 * a) if d >= 0: print(f"Real roots: {root1.real:g} and {root2.real:g}") else: print(f"Complex roots: {root1:.3g} and {root2:.3g}")

Output:

Solve ax^2 + bx + c = 0 a: 2 b: -7 c: 3 Real roots: 3 and 0.5
Command Prompt showing a Python quadratic equation program asking for a, b and c and printing real roots 3 and 0.52x² – 7x + 3 = 0 has roots 3 and 0.5.

Add a check for non-numeric input with try/except ValueError, as in the guess the number game.

How do you solve a quadratic word problem in Python?

A ball thrown upward at 48 ft/s from a 64 ft roof follows h(t) = -16t² + 48t + 64. The positive root is when it hits the ground, and the vertex is its highest point:

import math # a ball thrown up at 48 ft/s from a 64 ft rooftop: h(t) = -16t^2 + 48t + 64 a, b, c = -16, 48, 64 d = b * b - 4 * a * c t1, t2 = (-b + math.sqrt(d)) / (2 * a), (-b - math.sqrt(d)) / (2 * a) landing = max(t1, t2) # the negative root has no physical meaning peak_t = -b / (2 * a) peak_h = a * peak_t ** 2 + b * peak_t + c print(f"roots: {t1:g} s and {t2:g} s -> lands after {landing:g} seconds") print(f"highest point: {peak_h:g} ft at t = {peak_t:g} s")

Output:

roots: -1 s and 4 s -> lands after 4 seconds highest point: 100 ft at t = 1.5 s

Only one root makes sense physically, so I keep the positive one; the negative time is before the throw. The vertex formula -b / (2a) gives the peak without any square roots.

A quadratic formula precision trap with very large b

When your b is huge compared with a and c, the textbook formula subtracts two nearly equal numbers and loses precision. A rearranged formula fixes it:

import math a, b, c = 1.0, 1e8, 1.0 # roots near -1e8 and -1e-8 naive_small = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a) # subtracts two nearly equal numbers q = -0.5 * (b + math.copysign(math.sqrt(b * b - 4 * a * c), b)) stable_small = c / q # avoids the cancellation print(f"naive small root: {naive_small:.10e}") print(f"stable small root: {stable_small:.10e}") print(f"check a*x^2+bx+c: naive {a*naive_small**2 + b*naive_small + c:.2e}, stable {a*stable_small**2 + b*stable_small + c:.2e}")

Output:

naive small root: -7.4505805969e-09 stable small root: -1.0000000000e-08 check a*x^2+bx+c: naive 2.55e-01, stable 1.11e-16
Command Prompt output comparing a naive and a numerically stable Python quadratic formula for a tiny root with very large bThe naive small root is noticeably off; the stable version plugs back in with an error of essentially zero.

You’ll rarely hit this with classroom numbers, and I’ve only seen it in scientific code, but it matters in physics and engineering code with mixed scales.

More math programs in Python:

Frequently asked questions

How do I solve a quadratic equation in Python?

Compute d = b**2 - 4*a*c, then roots are (-b ± sqrt(d)) / (2*a). Use cmath.sqrt so negative d gives complex roots.

Why do I get a math domain error?

The discriminant is negative and math.sqrt can’t take negative numbers. Use cmath.sqrt.

How do I find complex roots?

Use cmath.sqrt in the formula, or numpy.roots([a, b, c]).

What does the discriminant tell me?

Positive: two real roots. Zero: one repeated root. Negative: two complex roots.

Can numpy.roots solve higher-degree equations?

Yes. Pass all the coefficients, highest power first, and it returns every root.

Where is cmath documented?

See cmath in the Python docs.

Read Entire Article