Quadratic Equation Solver

A complete walkthrough — the mathematics, the Python code, and every line explained.

This page explains a small Python program that solves quadratic equations of the form ax² + bx + c = 0. It does three things: it classifies the equation by its discriminant, it computes the roots using a numerically stable version of the quadratic formula, and it prints a human-readable, step-by-step derivation using proper mathematical symbols.

Contents

  1. The mathematics
  2. Numerical stability
  3. What the program prints
  4. The Python code (full listing)
  5. Line-by-line explanation
  6. How to run it

1. The mathematics

A quadratic equation is a polynomial equation of degree two:

ax² + bx + c = 0, a ≠ 0

The coefficients a, b, and c are real numbers. The condition a ≠ 0 is essential: if a = 0 the x² term disappears and the equation becomes linear, not quadratic. The program handles that degenerate case separately.

1.1 The quadratic formula

The roots — the values of x that satisfy the equation — are given by the quadratic formula:

−b ± √(b² − 4ac) x = ─────────────────── 2a

The expression under the square root is called the discriminant, usually written D or Δ:

D = b² − 4ac

1.2 The discriminant tells you everything

The sign of D decides how many real roots exist and what kind they are. This is the key to understanding the program's branching logic.

DiscriminantRootsExplanation
D > 0 Two distinct real roots √D is a positive real number, so the ± produces two different values.
D = 0 One repeated real root √D = 0, so both signs give the same value, x = −b / 2a.
D < 0 Two complex conjugate roots √D is imaginary. Writing √D = i·√|D| gives a real part and an imaginary part of opposite signs.

1.3 The complex case in detail

When D < 0, let |D| = −D. Then √D = i·√|D|, and the roots are

x = −b/(2a) ± i·√|D| / (2a)

Both roots share the same real part −b/(2a) and have imaginary parts of equal magnitude but opposite sign. Such a pair is called complex conjugates.

1.4 The degenerate case a = 0

If a = 0 the equation reduces to bx + c = 0, which has the single solution x = −c/b (provided b ≠ 0). If both a = 0 and b = 0, the equation is c = 0, which is either trivially true (no unique solution) or false — the program raises an error in this case.

2. Numerical stability — why not just plug in?

Applying the quadratic formula naively causes catastrophic cancellation when b² is much larger than 4ac. In that situation √(b² − 4ac) ≈ |b|, and the two terms in −b ± √D nearly cancel, destroying precision.

The standard fix is to compute the well-conditioned root first and derive the other from the relation between the roots and the coefficients (Vieta's formulas: x₁·x₂ = c/a). Specifically, choose

q = −½ · (b + sign(b)·√D)

so that the addition in the numerator never cancels. Then

x₁ = q/a, x₂ = c/q

This is the approach the program uses. When b = 0 the trick degenerates (the sign of zero is arbitrary), so the program falls back to the analytic symmetric roots x = ±√(−c/a).

3. What the program prints

The program does not just print the answer. It prints a worked derivation: the equation, the substitutions of a, b, c into the discriminant, the sign analysis, and the substitution into the quadratic formula. For example, running it on x² − 3x + 2 = 0 produces:

Equation: 1x² − 3x + 2 = 0 Form: ax² + bx + c = 0 Where: a = 1, b = −3, c = 2 ──────────────────────────────────────────────────────────── STEP 1 — The quadratic formula ──────────────────────────────────────────────────────────── For ax² + bx + c = 0, the roots are given by: −b ± √(b² − 4ac) x = ─────────────────── 2a We first compute the discriminant D = b² − 4ac. D tells us what kind of roots we get. ──────────────────────────────────────────────────────────── STEP 2 — Substitute a, b, c into D = b² − 4ac ──────────────────────────────────────────────────────────── D = b² − 4ac = (−3)² − 4·(1)·(2) = 9 − 8 = 1 So D = 1. ──────────────────────────────────────────────────────────── STEP 3 — Interpret D and solve ──────────────────────────────────────────────────────────── D = 1 > 0 ⟹ two distinct real roots. Compute √D: √(1) = 1 Substitute into the formula: x = ( −b ± √D ) / (2a) = ( −(−3) ± 1 ) / (2·(1)) Split into the two roots: x₁ = ( −(−3) − 1 ) / (2·(1)) = ( 3 − 1 ) / 2 = 1 x₂ = ( −(−3) + 1 ) / (2·(1)) = ( 3 + 1 ) / 2 = 2 ──────────────────────────────────────────────────────────── RESULT ──────────────────────────────────────────────────────────── x₁ = 1 x₂ = 2

Note that the roots are not sorted. x₁ is always the root using the minus sign before √D, and x₂ uses the plus sign — exactly matching the left-to-right reading of the formula −b ± √D.

4. The Python code (full listing)

The program is about 200 lines, including the step-by-step output logic. It depends only on the standard library (cmath, math, sys).

quadratic_solver.py
from __future__ import annotations

import cmath
import math
import sys

type Number = int | float | complex

_ZERO_TOL = 1e-12
_SIG_DIGITS = 12


def _clean(value: float, tol: float = _ZERO_TOL) -> float:
    if abs(value) < tol:
        return 0.0
    return round(value, _SIG_DIGITS) + 0.0


def _discriminant(a: float, b: float, c: float) -> float:
    return b * b - 4.0 * a * c


def _num(value: float) -> str:
    text = f"{_clean(float(value)):.6g}"
    return text.replace("-", "−")


def _paren(value: float) -> str:
    cleaned = _clean(float(value))
    text = f"{cleaned:.6g}".replace("-", "−")
    return text if cleaned >= 0 else f"({text})"


def solve_quadratic(a: float, b: float, c: float) -> list[Number]:
    if a == 0.0:
        if b == 0.0:
            raise ValueError("a and b are both zero: not a solvable quadratic equation.")
        return [-c / b]

    d = _discriminant(a, b, c)

    if d == 0.0:
        return [-b / (2.0 * a)]

    if d > 0.0:
        sqrt_d = math.sqrt(d)
        if b != 0.0:
            q = -0.5 * (b + math.copysign(sqrt_d, b))
            return [q / a, c / q]
        root = math.sqrt(-c / a)
        return [-root, root]

    two_a = 2.0 * a
    sqrt_d = cmath.sqrt(d)
    return [(-b - sqrt_d) / two_a, (-b + sqrt_d) / two_a]


def format_root(x: Number) -> str:
    if isinstance(x, complex):
        real = _clean(x.real)
        imag = _clean(x.imag)
        if imag == 0.0:
            return f"{real:.6g}".replace("-", "−")
        sign = "+" if imag > 0 else "−"
        mag = abs(imag)
        if real == 0.0:
            return f"{sign}{mag:.6g}i"
        return f"{real:.6g}".replace("-", "−") + f" {sign} {mag:.6g}i"

    return f"{_clean(float(x)):.6g}".replace("-", "−")


def build_equation_string(a: float, b: float, c: float) -> str:
    terms: list[str] = []
    for coef, var in ((a, "x²"), (b, "x"), (c, "")):
        if coef == 0 and var:
            continue
        if not terms:
            terms.append(f"{coef:g}{var}".replace("-", "−"))
        else:
            op = "+" if coef > 0 else "−"
            terms.append(f"{op} {abs(coef):g}{var}")
    return f"{' '.join(terms)} = 0" if terms else "0 = 0"


def _show_steps(a: float, b: float, c: float) -> None:
    print(f"Equation:  {build_equation_string(a, b, c)}")
    print(f"Form:      ax² + bx + c = 0")
    print(f"Where:     a = {_num(a)},   b = {_num(b)},   c = {_num(c)}")

    if a == 0.0:
        print()
        print("Since a = 0, the x² term vanishes. The equation is linear:")
        print(f"    {_num(b)}x + {_num(c)} = 0")
        print()
        print("Move the constant to the right side:")
        print(f"    {_num(b)}x = −({_num(c)})")
        print()
        print(f"Divide both sides by {_num(b)}:")
        print(f"    x = −({_num(c)}) / ({_num(b)})")
        print()
        print(f"    x = {_num(-c / b)}")
        return

    print()
    print("─" * 60)
    print("STEP 1 — The quadratic formula")
    print("─" * 60)
    print("    For ax² + bx + c = 0, the roots are given by:")
    print()
    print("             −b ± √(b² − 4ac)")
    print("        x = ───────────────────")
    print("                     2a")
    print()
    print("We first compute the discriminant  D = b² − 4ac.")
    print("D tells us what kind of roots we get.")

    print()
    print("─" * 60)
    print("STEP 2 — Substitute a, b, c into D = b² − 4ac")
    print("─" * 60)
    print("    D = b² − 4ac")
    print(f"      = {_paren(b)}² − 4·{_paren(a)}·{_paren(c)}")
    b2 = b * b
    four_ac = 4.0 * a * c
    d = b2 - four_ac
    print(f"      = {_num(b2)} − {_num(four_ac)}")
    print(f"      = {_num(d)}")
    print()
    print(f"    So  D = {_num(d)}.")

    print()
    print("─" * 60)
    print("STEP 3 — Interpret D and solve")
    print("─" * 60)

    if d > 0.0:
        sqrt_d = math.sqrt(d)
        x1 = (-b - sqrt_d) / (2.0 * a)
        x2 = (-b + sqrt_d) / (2.0 * a)

        print(f"    D = {_num(d)} > 0  ⟹  two distinct real roots.")
        print()
        print("    Compute √D:")
        print(f"        √({_num(d)}) = {_num(sqrt_d)}")
        print()
        print("    Substitute into the formula:")
        print(f"        x = ( −b ± √D ) / (2a)")
        print(f"          = ( −{_paren(b)} ± {_num(sqrt_d)} ) / (2·{_paren(a)})")
        print()
        print("    Split into the two roots:")
        print(f"        x₁ = ( −{_paren(b)} − {_num(sqrt_d)} ) / (2·{_paren(a)})")
        print(f"           = ( {_num(-b)} − {_num(sqrt_d)} ) / {_num(2.0 * a)}")
        print(f"           = {_num(x1)}")
        print()
        print(f"        x₂ = ( −{_paren(b)} + {_num(sqrt_d)} ) / (2·{_paren(a)})")
        print(f"           = ( {_num(-b)} + {_num(sqrt_d)} ) / {_num(2.0 * a)}")
        print(f"           = {_num(x2)}")
        print()
        print("─" * 60)
        print("RESULT")
        print("─" * 60)
        print(f"    x₁ = {_num(x1)}")
        print(f"    x₂ = {_num(x2)}")

    elif d == 0.0:
        x = -b / (2.0 * a)
        print(f"    D = {_num(d)} = 0  ⟹  one repeated real root.")
        print()
        print("    When D = 0, the ± term disappears, so:")
        print("        x = −b / (2a)")
        print()
        print("    Substitute:")
        print(f"        x = −{_paren(b)} / (2·{_paren(a)})")
        print(f"          = {_num(-b)} / {_num(2.0 * a)}")
        print(f"          = {_num(x)}")
        print()
        print("─" * 60)
        print("RESULT")
        print("─" * 60)
        print(f"    x₁ = x₂ = {_num(x)}   (repeated root)")

    else:
        abs_d = -d
        sqrt_abs_d = math.sqrt(abs_d)
        re = -b / (2.0 * a)
        im = sqrt_abs_d / (2.0 * a)
        root1 = complex(re, -abs(im))
        root2 = complex(re, abs(im))

        print(f"    D = {_num(d)} < 0  ⟹  two complex conjugate roots.")
        print()
        print("    A negative D means √D is imaginary. Write:")
        print("        √D = i·√|D|")
        print()
        print("    Compute |D| and √|D|:")
        print(f"        |D| = {_num(abs_d)}")
        print(f"        √|D| = {_num(sqrt_abs_d)}")
        print(f"        √D = {_num(sqrt_abs_d)}i")
        print()
        print("    Substitute into the formula:")
        print(f"        x = ( −b ± √D ) / (2a)")
        print(f"          = ( −{_paren(b)} ± {_num(sqrt_abs_d)}i ) / (2·{_paren(a)})")
        print()
        print("    Real part:")
        print(f"        Re = −b / (2a) = −{_paren(b)} / (2·{_paren(a)})")
        print(f"           = {_num(-b)} / {_num(2.0 * a)}")
        print(f"           = {_num(re)}")
        print()
        print("    Imaginary part:")
        print(f"        Im = ±√|D| / (2a) = ±{_num(sqrt_abs_d)} / {_num(2.0 * a)}")
        print(f"           = ±{_num(im)}")
        print()
        print("─" * 60)
        print("RESULT")
        print("─" * 60)
        print(f"    x₁ = {format_root(root1)}")
        print(f"    x₂ = {format_root(root2)}")


def _parse_coefficients(argv: list[str]) -> tuple[float, float, float]:
    if len(argv) == 4:
        try:
            a, b, c = (float(v) for v in argv[1:4])
        except ValueError as exc:
            raise SystemExit(
                "Coefficients must be numbers, e.g. python quadratic_solver.py 1 -3 2"
            ) from exc
        return a, b, c

    if len(argv) == 1:
        print("Solve ax² + bx + c = 0")
        try:
            return (
                float(input("a = ")),
                float(input("b = ")),
                float(input("c = ")),
            )
        except (ValueError, EOFError) as exc:
            raise SystemExit("Please enter numeric coefficients.") from exc

    raise SystemExit("Usage: python quadratic_solver.py a b c")


def main() -> None:
    a, b, c = _parse_coefficients(sys.argv)

    try:
        solve_quadratic(a, b, c)
    except ValueError as exc:
        sys.exit(str(exc))

    print()
    _show_steps(a, b, c)


if __name__ == "__main__":
    main()

5. Line-by-line explanation

Each block below shows a numbered excerpt of the code, followed by a walkthrough of what each line does and why it is there.

Imports and type alias
1from __future__ import annotations
2
3import cmath
4import math
5import sys
6
7type Number = int | float | complex
8
9_ZERO_TOL = 1e-12
10_SIG_DIGITS = 12

What's happening

_clean — snap near-zero floats and trim precision
11def _clean(value: float, tol: float = _ZERO_TOL) -> float:
12    if abs(value) < tol:
13        return 0.0
14    return round(value, _SIG_DIGITS) + 0.0

What's happening

_discriminant — the heart of the classification
15def _discriminant(a: float, b: float, c: float) -> float:
16    return b * b - 4.0 * a * c

What's happening

_num and _paren — formatting helpers
17def _num(value: float) -> str:
18    text = f"{_clean(float(value)):.6g}"
19    return text.replace("-", "−")
20
21def _paren(value: float) -> str:
22    cleaned = _clean(float(value))
23    text = f"{cleaned:.6g}".replace("-", "−")
24    return text if cleaned >= 0 else f"({text})"

What's happening

solve_quadratic — the numerical core
25def solve_quadratic(a: float, b: float, c: float) -> list[Number]:
26    if a == 0.0:
27        if b == 0.0:
28            raise ValueError("a and b are both zero: not a solvable quadratic equation.")
29        return [-c / b]
30
31    d = _discriminant(a, b, c)
32
33    if d == 0.0:
34        return [-b / (2.0 * a)]
35
36    if d > 0.0:
37        sqrt_d = math.sqrt(d)
38        if b != 0.0:
39            q = -0.5 * (b + math.copysign(sqrt_d, b))
40            return [q / a, c / q]
41        root = math.sqrt(-c / a)
42        return [-root, root]
43
44    two_a = 2.0 * a
45    sqrt_d = cmath.sqrt(d)
46    return [(-b - sqrt_d) / two_a, (-b + sqrt_d) / two_a]

What's happening

format_root — render a single root
47def format_root(x: Number) -> str:
48    if isinstance(x, complex):
49        real = _clean(x.real)
50        imag = _clean(x.imag)
51        if imag == 0.0:
52            return f"{real:.6g}".replace("-", "−")
53        sign = "+" if imag > 0 else "−"
54        mag = abs(imag)
55        if real == 0.0:
56            return f"{sign}{mag:.6g}i"
57        return f"{real:.6g}".replace("-", "−") + f" {sign} {mag:.6g}i"
58
59    return f"{_clean(float(x)):.6g}".replace("-", "−")

What's happening

build_equation_string — human-readable equation
60def build_equation_string(a: float, b: float, c: float) -> str:
61    terms: list[str] = []
62    for coef, var in ((a, "x²"), (b, "x"), (c, "")):
63        if coef == 0 and var:
64            continue
65        if not terms:
66            terms.append(f"{coef:g}{var}".replace("-", "−"))
67        else:
68            op = "+" if coef > 0 else "−"
69            terms.append(f"{op} {abs(coef):g}{var}")
70    return f"{' '.join(terms)} = 0" if terms else "0 = 0"

What's happening

_show_steps — the step-by-step derivation (header and linear branch)
71def _show_steps(a: float, b: float, c: float) -> None:
72    print(f"Equation:  {build_equation_string(a, b, c)}")
73    print(f"Form:      ax² + bx + c = 0")
74    print(f"Where:     a = {_num(a)},   b = {_num(b)},   c = {_num(c)}")
75
76    if a == 0.0:
77        print()
78        print("Since a = 0, the x² term vanishes. The equation is linear:")
79        print(f"    {_num(b)}x + {_num(c)} = 0")
80        print()
81        print("Move the constant to the right side:")
82        print(f"    {_num(b)}x = −({_num(c)})")
83        print()
84        print(f"Divide both sides by {_num(b)}:")
85        print(f"    x = −({_num(c)}) / ({_num(b)})")
86        print()
87        print(f"    x = {_num(-c / b)}")
88        return

What's happening

_show_steps — STEP 1 (formula) and STEP 2 (discriminant substitution)
89    print()
90    print("─" * 60)
91    print("STEP 1 — The quadratic formula")
92    print("─" * 60)
93    print("    For ax² + bx + c = 0, the roots are given by:")
94    print()
95    print("             −b ± √(b² − 4ac)")
96    print("        x = ───────────────────")
97    print("                     2a")
98    print()
99    print("We first compute the discriminant  D = b² − 4ac.")
100    print("D tells us what kind of roots we get.")
101
102    print()
103    print("─" * 60)
104    print("STEP 2 — Substitute a, b, c into D = b² − 4ac")
105    print("─" * 60)
106    print("    D = b² − 4ac")
107    print(f"      = {_paren(b)}² − 4·{_paren(a)}·{_paren(c)}")
108    b2 = b * b
109    four_ac = 4.0 * a * c
110    d = b2 - four_ac
111    print(f"      = {_num(b2)} − {_num(four_ac)}")
112    print(f"      = {_num(d)}")
113    print()
114    print(f"    So  D = {_num(d)}.")

What's happening

_show_steps — STEP 3, real roots (D > 0)
115    print()
116    print("─" * 60)
117    print("STEP 3 — Interpret D and solve")
118    print("─" * 60)
119
120    if d > 0.0:
121        sqrt_d = math.sqrt(d)
122        x1 = (-b - sqrt_d) / (2.0 * a)
123        x2 = (-b + sqrt_d) / (2.0 * a)
124
125        print(f"    D = {_num(d)} > 0  ⟹  two distinct real roots.")
126        print()
127        print("    Compute √D:")
128        print(f"        √({_num(d)}) = {_num(sqrt_d)}")
129        print()
130        print("    Substitute into the formula:")
131        print(f"        x = ( −b ± √D ) / (2a)")
132        print(f"          = ( −{_paren(b)} ± {_num(sqrt_d)} ) / (2·{_paren(a)})")
133        print()
134        print("    Split into the two roots:")
135        print(f"        x₁ = ( −{_paren(b)} − {_num(sqrt_d)} ) / (2·{_paren(a)})")
136        print(f"           = ( {_num(-b)} − {_num(sqrt_d)} ) / {_num(2.0 * a)}")
137        print(f"           = {_num(x1)}")
138        print()
139        print(f"        x₂ = ( −{_paren(b)} + {_num(sqrt_d)} ) / (2·{_paren(a)})")
140        print(f"           = ( {_num(-b)} + {_num(sqrt_d)} ) / {_num(2.0 * a)}")
141        print(f"           = {_num(x2)}")
142        print()
143        print("─" * 60)
144        print("RESULT")
145        print("─" * 60)
146        print(f"    x₁ = {_num(x1)}")
147        print(f"    x₂ = {_num(x2)}")

What's happening

_show_steps — repeated root (D = 0)
148    elif d == 0.0:
149        x = -b / (2.0 * a)
150        print(f"    D = {_num(d)} = 0  ⟹  one repeated real root.")
151        print()
152        print("    When D = 0, the ± term disappears, so:")
153        print("        x = −b / (2a)")
154        print()
155        print("    Substitute:")
156        print(f"        x = −{_paren(b)} / (2·{_paren(a)})")
157        print(f"          = {_num(-b)} / {_num(2.0 * a)}")
158        print(f"          = {_num(x)}")
159        print()
160        print("─" * 60)
161        print("RESULT")
162        print("─" * 60)
163        print(f"    x₁ = x₂ = {_num(x)}   (repeated root)")

What's happening

_show_steps — complex roots (D < 0)
164    else:
165        abs_d = -d
166        sqrt_abs_d = math.sqrt(abs_d)
167        re = -b / (2.0 * a)
168        im = sqrt_abs_d / (2.0 * a)
169        root1 = complex(re, -abs(im))
170        root2 = complex(re, abs(im))

        print(f"    D = {_num(d)} < 0  ⟹  two complex conjugate roots.")
        print()
        print("    A negative D means √D is imaginary. Write:")
        print("        √D = i·√|D|")
        print()
        print("    Compute |D| and √|D|:")
        print(f"        |D| = {_num(abs_d)}")
        print(f"        √|D| = {_num(sqrt_abs_d)}")
        print(f"        √D = {_num(sqrt_abs_d)}i")
        print()
        print("    Substitute into the formula:")
        print(f"        x = ( −b ± √D ) / (2a)")
        print(f"          = ( −{_paren(b)} ± {_num(sqrt_abs_d)}i ) / (2·{_paren(a)})")
        print()
        print("    Real part:")
        print(f"        Re = −b / (2a) = −{_paren(b)} / (2·{_paren(a)})")
        print(f"           = {_num(-b)} / {_num(2.0 * a)}")
        print(f"           = {_num(re)}")
        print()
        print("    Imaginary part:")
        print(f"        Im = ±√|D| / (2a) = ±{_num(sqrt_abs_d)} / {_num(2.0 * a)}")
        print(f"           = ±{_num(im)}")
        print()
        print("─" * 60)
        print("RESULT")
        print("─" * 60)
        print(f"    x₁ = {format_root(root1)}")
        print(f"    x₂ = {format_root(root2)}")

What's happening

_parse_coefficients — accept argv or prompt
171def _parse_coefficients(argv: list[str]) -> tuple[float, float, float]:
172    if len(argv) == 4:
173        try:
174            a, b, c = (float(v) for v in argv[1:4])
175        except ValueError as exc:
176            raise SystemExit(
177                "Coefficients must be numbers, e.g. python quadratic_solver.py 1 -3 2"
178            ) from exc
179        return a, b, c
180
181    if len(argv) == 1:
182        print("Solve ax² + bx + c = 0")
183        try:
184            return (
185                float(input("a = ")),
186                float(input("b = ")),
187                float(input("c = ")),
188            )
189        except (ValueError, EOFError) as exc:
190            raise SystemExit("Please enter numeric coefficients.") from exc
191
192    raise SystemExit("Usage: python quadratic_solver.py a b c")

What's happening

main — wire everything together
193def main() -> None:
194    a, b, c = _parse_coefficients(sys.argv)
195
196    try:
197        solve_quadratic(a, b, c)
198    except ValueError as exc:
199        sys.exit(str(exc))
200
201    print()
202    _show_steps(a, b, c)
203
204
205if __name__ == "__main__":
206    main()

What's happening

6. How to run it

Save the code as quadratic_solver.py, then run it with three coefficients on the command line:

python3 quadratic_solver.py 1 -3 2

Or run it with no arguments to be prompted interactively:

python3 quadratic_solver.py Solve ax² + bx + c = 0 a = 1 b = -3 c = 2

Both forms produce the same step-by-step derivation shown in section 3.