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
A quadratic equation is a polynomial equation of degree two:
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:
The expression under the square root is called the discriminant, usually
written D or Δ:
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.
| Discriminant | Roots | Explanation |
|---|---|---|
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
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
so that the addition in the numerator never cancels. Then
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:
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).
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.
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
- Line 1.
from __future__ import annotationsmakes type hints lazy (strings under the hood), so forward references and built-in generics likelist[int]work on any Python version and cost nothing at runtime. - Lines 3–5. Three standard-library modules.
cmathsupplies complex square roots (cmath.sqrt), unlikemath.sqrtwhich raises on negatives.mathsupplies realsqrtandcopysign.sysis used forsys.argvandsys.exit. - Line 7. A type alias (PEP 695 syntax). It says: wherever
Numberappears as a type, the value is anint,float, orcomplex. This documents the intended return type ofsolve_quadratic. - Lines 9–10. Two module-level constants.
_ZERO_TOLis the threshold below which a float is treated as zero when cleaning up noise._SIG_DIGITSis the number of significant digits kept when rounding. The leading underscore signals that they are internal.
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
- Line 11. A pure helper. The default argument
tol=_ZERO_TOLmakes the tolerance overridable but rarely changed. - Line 12. If the magnitude is below the tolerance, the value is
floating-point fuzz — e.g.
2.220446049250313e-16left over from a subtraction that should have been exactly zero. - Line 13. Return clean
+0.0instead of the tiny residue. This prevents printing things like−2.2e-16ifor what should be a real root. - Line 14. Otherwise round to 12 decimal places and add
0.0. The+ 0.0normalizes negative zero (−0.0) to positive zero, since−0.0 + 0.0 == 0.0.
15def _discriminant(a: float, b: float, c: float) -> float:
16 return b * b - 4.0 * a * c
What's happening
- Line 16. Computes
D = b² − 4acexactly as the mathematics says. Writing4.0instead of4forces a float result even when all inputs are ints, keeping the return type consistent.
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
- Line 18. Clean the value, then format with
:gat six significant figures. The:gformat drops trailing zeros and switches to scientific notation for very large or small numbers — ideal for a display string. - Line 19. Replace ASCII hyphen-minus
"-"with the Unicode minus sign"−"(U+2212). The two look similar but the latter is the typographically correct symbol for negation and matches the±symbol. - Line 22. Same cleaning as
_num. - Lines 23–24. Format the cleaned value, then wrap it in parentheses
only if it is negative. This is what makes the printed formula show
−(−3)rather than the confusing−−3when substituting a negativeb.
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
- Line 25. Public entry point. Returns a list because there can be
one or two roots. The
Numberalias signals that complex values are possible. - Line 26. First branch: what if
a = 0? Then the equation is not quadratic. We handle it before computing the discriminant, becauseD = b² − 4acwould still be computable but meaningless for classifying roots. - Lines 27–28. If
a = 0andb = 0, the equation isc = 0, which has no unique solution. RaiseValueErrorso the caller can decide how to report it. - Line 29. The linear case:
bx + c = 0has solutionx = −c/b. Return as a one-element list. - Line 31. Compute the discriminant once; reuse it for
classification and for
sqrt(D). - Lines 33–34.
D = 0⟹ one repeated real root. The±√Dterm disappears, leavingx = −b/(2a). - Line 36.
D > 0⟹ two distinct real roots. - Line 37. Real square root of a positive number — safe with
math.sqrt. - Line 38. The numerically stable branch only makes sense when
b ≠ 0, becausecopysign(sqrt_d, b)would otherwise use the arbitrary sign of zero. - Line 39. The stable quantity
q = −½·(b + sign(b)·√D). The sign matching means the two terms being added never cancel — the whole point of the trick. - Line 40. The two roots via Vieta's relations:
x₁ = q/aandx₂ = c/q. No sorting. - Lines 41–42. Fallback when
b = 0. The equation isax² + c = 0, sox = ±√(−c/a). Return in the natural order[−root, root], matching the∓order of the formula. - Line 44. Precompute
2aso it is not recomputed twice. - Line 45.
cmath.sqrtof a negative number returns a complex number with zero real part and positive imaginary part, e.g.cmath.sqrt(−4) = 2i. - Line 46. The two complex conjugate roots, in formula order: the
minus sign first, the plus sign second.
x₁corresponds to−√D,x₂to+√D.
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
- Line 48. Complex roots need special formatting; real roots do not.
isinstancedistinguishes the two. - Lines 49–50. Extract and clean the real and imaginary parts. The
cleaning matters:
cmath.sqrtcan produce tiny fuzz like1e-17iwhere zero is expected. - Lines 51–52. If the imaginary part cleaned to zero, treat the
value as a real number and print it plainly. This handles the rare case where
cmathreturns a complex with zero imaginary part. - Line 53. Decide the sign character:
+or the Unicode−. - Lines 55–56. Purely imaginary case, e.g.
2ior−2i— omit the real part and its sign. - Line 57. General complex case, e.g.
1 + 2ior1 − 2i. Use spaces around the sign for readability. - Line 59. Real path. Cast to
float(in case an int arrived), clean, format, replace the minus sign.
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
- Line 62. Iterate over the three coefficient/variable pairs. Using a tuple of tuples keeps the code compact and makes the pattern obvious: each term is "coefficient times variable".
- Lines 63–64. Skip a term whose coefficient is zero — unless
it is the constant term (
var == ""), in which case a zero constant is conventionally omitted too, but thevarguard keeps the logic explicit. In practice both zeroaand zerobare skipped; a zerocis also skipped becausevaris empty, socoef == 0 and varisFalse. The+ 0shown in output is therefore never emitted. - Lines 65–66. The first term has no leading sign; if it is negative, the minus sign is part of the coefficient, so we just replace the character.
- Lines 67–69. Subsequent terms need an explicit operator. Compute the sign from the coefficient's sign, then print the absolute value with the operator in front — this matches how people write equations.
- Line 70. Join with spaces and append
= 0. Theelse "0 = 0"fallback handles the degenerate all-zero input gracefully instead of producing an empty string.
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
- Line 71. Prints the derivation; returns nothing. It is separated
from
solve_quadraticso the numerical function stays pure and testable. - Lines 72–74. Header block: the equation, the symbolic form, and the three coefficients. This is the "given" of the worked solution.
- Line 76. Mirror the same branch structure as
solve_quadratic, so the displayed derivation never disagrees with the computed result. - Lines 77–87. The linear case is worked out as three mini-steps:
write the equation, move the constant, divide. Each line shows the actual numbers in
place. Blank
print()calls separate the steps visually. - Line 88. Return early — the rest of the function is quadratic-only.
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
- Lines 90–92. A visual rule and the step heading. Using
"─" * 60draws a consistent horizontal line of 60 box-drawing characters. - Lines 93–97. The symbolic formula itself, laid out with
±,√, and a drawn fraction bar. This is what the reader will be substituting into. - Lines 99–100. Explain why we compute
Dfirst: it tells us what kind of roots to expect. This is the pedagogical point of step 2. - Line 106. The symbolic form
D = b² − 4ac. - Line 107. The same line with
a,b,csubstituted in, wrapped by_parenso negative values show as(−3). - Lines 108–110. Compute
b²and4acseparately — this lets us print them on their own line, showing the reader the intermediate values before the subtraction. - Lines 111–112. The simplified line
= 9 − 8and the result= 1. Each step of arithmetic appears on its own line, exactly as a student would write it. - Line 114. Restate the final discriminant so the reader carries it into step 3.
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
- Line 120. Branch on
D > 0. Because the discriminant was computed once in step 2 and saved ind, this condition matches exactly what was printed. - Lines 121–123. Compute
√Dand the two roots explicitly with the−/+split.x1always uses the minus sign andx2the plus sign — no sorting. - Line 125. State the classification:
D > 0implies two distinct real roots. The⟹symbol makes the logical implication clear. - Lines 127–128. Show the square-root computation on its own line.
- Lines 131–132. Show the formula, then the formula with numbers substituted. This is the "before" and "after" of the substitution.
- Lines 135–141. The two roots are each shown as a three-line
derivation: the formula with
±resolved, the numerator and denominator simplified, and the final value. The reader can follow the arithmetic on every line. - Lines 143–147. A clear
RESULTblock separates the derivation from the answer.
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
- Line 148. The
D = 0branch. - Line 149. The single root
−b/(2a). Because√0 = 0, the two signs coincide, so only one value is computed. - Lines 152–153. Explain why the formula reduces: the
±√Dterm vanishes. - Lines 155–158. The substitution, the simplified numerator and denominator, and the final value — same three-line pattern as the real case.
- Line 163. Print
x₁ = x₂ = …to emphasise that the two roots are the same value. This is the mathematical meaning of a repeated root.
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
- Line 164. The
D < 0branch — complex roots. - Line 165.
|D| = −Dis the magnitude of the discriminant. - Line 166.
√|D|is the magnitude of the imaginary part before dividing by2a. - Lines 167–168. The real part
re = −b/(2a)and the imaginary magnitudeim = √|D|/(2a). - Lines 169–170. Build the two conjugate complex roots.
root1uses the minus sign on the imaginary part (matching−√D),root2uses the plus sign — again, no sorting. - The first print. State the classification:
D < 0implies two complex conjugate roots. - Then the block explains that
√D = i·√|D|and shows|D|,√|D|, and√Das a sequence of lines. - Real part and Imaginary part are each derived in three lines: symbolic form, substitution, final value.
- The RESULT block uses
format_rootto render the complex numbers in thea + biform with the Unicode minus.
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
- Line 172. If exactly three arguments follow the script name
(
len(argv) == 4), parse them from the command line. - Lines 173–178. Convert the three strings to
float. If any fails, raiseSystemExitwith a helpful message.SystemExitis used rather thanValueErrorbecause this is a user-input error, not a programming error. - Line 179. Return the tuple
(a, b, c). - Lines 181–188. If no arguments were given, prompt interactively.
input()returns a string;float()parses it.EOFErroris caught alongsideValueErrorso pressing Ctrl-D doesn't crash with a traceback. - Line 192. Any other argument count is a usage error.
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
- Line 194. Get the coefficients either from argv or from prompts.
- Lines 196–199. Call
solve_quadraticonce, purely to surface the degenerate-input error early. Ifa = b = 0, print the error and exit before printing any derivation. - Line 201. Blank line for spacing.
- Line 202. Print the full step-by-step walkthrough.
- Lines 205–206. Standard guard: run
main()only when the script is executed directly, not when imported as a module.
6. How to run it
Save the code as quadratic_solver.py, then run it with three
coefficients on the command line:
Or run it with no arguments to be prompted interactively:
Both forms produce the same step-by-step derivation shown in section 3.