Sub topic 12
Cancellation error when computing roots
The quadratic formula is exact in algebra. A computer stores real numbers with about 16 significant digits, so the same formula can lose most of those digits for some inputs. This chapter shows where the loss happens, how to predict it, and how to avoid it with the sum-and-product relations from the previous chapter.
Prerequisites. You should know the quadratic formula, the discriminant, and the Vieta relations: the roots satisfy x₁ + x₂ = −b/a and x₁x₂ = c/a. You should also be able to read short Python programs. Floating-point details are explained as they come up.
Floating-point numbers in one paragraph
A Python float is a 64-bit binary number with a 53-bit significand. That gives about 15 to 16 correct decimal digits. Every result is rounded to the nearest representable value, so it has a relative error of at most about 1.1 × 10⁻¹⁶. This bound is called the unit roundoff, written ε.
Rounding a single operation is almost always harmless. The trouble starts when a later step amplifies that tiny error.
What cancellation is
Cancellation happens when you subtract two numbers that are nearly equal. Suppose x and y each carry a relative error of about 10⁻¹⁶, and x − y is much smaller than either. The leading digits of x and y agree and vanish in the subtraction. What remains is mostly the old rounding noise.
The subtraction itself is exact. The damage was done earlier, when x and y were rounded. The subtraction exposes that error by removing the digits that hid it.
A decimal analogy with 8 significant digits:
| Quantity | Value |
|---|---|
| x | 1.2345678 |
| y | 1.2345671 |
| x − y | 0.0000007 |
Both inputs had 8 digits, but the difference has 1 meaningful digit. If the last digit of x or y was off by one, the difference could be 0.0000006 or 0.0000008. That is a relative error of about 14%, even though the inputs were accurate to about one part in 10⁷.
Where the quadratic formula cancels
Take x² + 10⁸x + 1 = 0, so a = 1, b = 10⁸ and c = 1. The exact roots are close to −10⁸ and −10⁻⁸. Their product is c/a = 1, which matches.
The discriminant is b² − 4ac = 10¹⁶ − 4, and its square root is very close to b:
√(10¹⁶ − 4) = 10⁸ · √(1 − 4 × 10⁻¹⁶) ≈ 10⁸ − 2 × 10⁻⁸
The formula for the small root is (−b + √d)/(2a), which is (−10⁸ + (10⁸ − 2 × 10⁻⁸))/2. The numerator subtracts two numbers of size 10⁸ to get a result of size 10⁻⁸. That is a loss of 16 orders of magnitude, which is all the digits a float has.
The loss is worse than the cancellation alone suggests. Near 10⁸, adjacent doubles are 2⁻²⁶ ≈ 1.49 × 10⁻⁸ apart. The computed square root can only be 10⁸ − 1.49 × 10⁻⁸ or 10⁸ − 2.98 × 10⁻⁸. The true value, 10⁸ − 2 × 10⁻⁸, rounds to the first. The numerator then becomes −1.49 × 10⁻⁸ instead of −2 × 10⁻⁸.
import math
def naive_roots(a, b, c):
r = math.sqrt(b * b - 4 * a * c)
return (-b - r) / (2 * a), (-b + r) / (2 * a)
def fmt(values):
return [format(v, ".10e") for v in values]
a, b, c = 1, 1e8, 1
x1, x2 = naive_roots(a, b, c)
print("naive roots :", fmt([x1, x2]))
print("product :", x1 * x2, "(should be c/a = 1)")The large root comes out as about −1.0000000000e+08, which is correct. The small root comes out as about −7.45e-09, not −1.00e-08. That is a relative error of roughly 25%, and not one significant digit is right. The product x₁x₂ is about 0.745 instead of 1, which exposes the problem.
Predicting the damage
Cancellation in the formula appears when 4|ac| is tiny compared with b². Then √d ≈ |b|, and one of the two numerators −b ± √d subtracts nearly equal numbers. The other adds two numbers of the same sign and is safe.
The small root is about |c/b|, while the rounding error in the numerator is about ε|b|. The relative error of the small root is therefore roughly:
ε · b² / |ac|
For b = 10⁸ and a = c = 1, this is about 10⁻¹⁶ · 10¹⁶ = 1, so all the digits are gone. For b = 10⁴ it is about 10⁻⁸, so you keep about 8 digits. Use the estimate to decide whether the issue matters for your data. If b² is within a few orders of magnitude of |ac|, the naive formula is fine.
Cancellation affects only the real-root branch. When d < 0 the roots are −b/(2a) ± i√(−d)/(2a). The real part involves no subtraction of nearly equal numbers, and the imaginary part is a single square root.
Which root is at risk
Which root cancels depends on the sign of b, because √d ≈ |b|.
| Sign of b | Risky numerator | Safe numerator |
|---|---|---|
| b > 0 | −b + √d (subtracts) | −b − √d (adds two negatives) |
| b < 0 | −b − √d (subtracts) | −b + √d (adds two positives) |
The safe numerator always has the form −(b + sign(b)·√d). Computing it adds two quantities of the same sign, so no digits are lost.
The fix: use the sign of b, then Vieta
- Compute the safe quantity q = −(b + sign(b)·√d)/2.
- Take the first root as x₁ = q/a. This is the large-magnitude root, computed without cancellation.
- Take the second root from the product relation, x₂ = c/q.
To see why step 3 is correct, note that x₁ · x₂ = (q/a)(c/q) = c/a, which is Vieta's product. Division by q does not cancel anything, so x₂ keeps full relative accuracy.
Here is a complete implementation:
import math
def stable_roots(a, b, c):
if a == 0:
raise ValueError("a must be nonzero")
d = b * b - 4 * a * c
if d < 0:
raise ValueError("negative discriminant: roots are complex")
q = -(b + math.copysign(math.sqrt(d), b)) / 2
if q == 0:
return 0.0, 0.0
return q / a, c / q
def fmt(values):
return [format(v, ".10e") for v in values]
x1, x2 = stable_roots(1, 1e8, 1)
print("stable roots:", fmt([x1, x2]))
print("product :", x1 * x2, "(should be c/a = 1)")
print("check small :", stable_roots(1, -3, 2))For x² + 10⁸x + 1 the output is about −1.0000000000e+08 and −1.0000000000e-08, and the product is 1 to within rounding. The small root now has about 16 correct digits. The last line prints (2.0, 1.0), so the function still works on ordinary inputs.
Three details matter:
math.copysign(x, b)gives the sign of b, and it returns +|x| when b is +0.0. With b = 0 the formula still works, because there is nothing to cancel.- The case q = 0 happens only when b = 0 and d = 0, which means c = 0. The equation is ax² = 0, with a double root at 0. Without the check,
c / qwould divide by zero. - When c = 0 and b ≠ 0, q = −b, so the roots are −b/a and 0.0. This is correct.
What the fix does not solve
Cancellation can also occur inside the discriminant, when b² ≈ 4ac. This is the case of two nearly equal roots. Here d is the difference of two nearly equal numbers, and its relative error can be large.
The stable formula does not remove this. Nearly equal roots are sensitive to small changes in the coefficients, so even an exact algorithm applied to rounded coefficients gives a visible error. The error is in the problem, not the method. The sensitivity grows roughly like ε/√|d|. For a double root, a change of ε in the coefficients can move the roots by about √ε ≈ 10⁻⁸. Nothing in plain double precision recovers the lost accuracy. If you need it, use higher precision such as Python's decimal or fractions, or exact integer arithmetic when the coefficients are integers.
Overflow is a separate failure. If |b| is above about 10¹⁵⁴, then b * b exceeds the range of a double and becomes inf. Scaling the coefficients first, for example dividing all three by max(|a|, |b|, |c|), avoids this without changing the roots.
Summary of the decision criteria
| Situation | What to do | Column | Column |
|---|---|---|---|
| b² is not much larger than \ | 4ac\ | The textbook formula is fine. | |
| b² ≫ \ | 4ac\ | and the roots are real | Use q = −(b + sign(b)·√d)/2, then q/a and c/q. |
| d < 0 | Use the complex formula. There is no cancellation. | ||
| b² ≈ 4ac (roots nearly equal) | Expect sensitivity. Use higher precision or exact arithmetic if you need more digits. | ||
| Coefficients extremely large or small | Scale them first to avoid overflow and underflow. |
Exercise
For x² − 10⁸x + 1 = 0, which of the two textbook formulas, (−b − √d)/(2a) or (−b + √d)/(2a), suffers cancellation, and why?
Show answer
Here b = −10⁸ is negative, so −b = 10⁸ is positive and √d ≈ 10⁸. The expression (−b − √d)/(2a) subtracts two nearly equal positive numbers, so it cancels. This is the small root, about 10⁻⁸. The "+" formula adds two positive numbers and is safe. In general, the formula that subtracts is the one where −b and ±√d have opposite signs.
Exercise
A program computes the large root of x² + 10⁸x + 1 = 0 as x₁ = −10⁸ (accurate). Use Vieta's product relation to get the small root without any subtraction.
Show answer
The product of the roots is c/a = 1, so x₂ = c/(a·x₁) = 1/(1 · (−10⁸)) = −10⁻⁸. This uses one division and no subtraction, so x₂ keeps full relative accuracy. It is the same step as x₂ = c/q in the stable algorithm.
Exercise
Using the estimate ε · b²/|ac| with ε ≈ 10⁻¹⁶, about how many correct digits does the naive formula give for the small root of x² + 10⁶x + 1 = 0?
Show answer
Here b² = 10¹² and |ac| = 1, so the relative error is about 10⁻¹⁶ · 10¹² = 10⁻⁴. That leaves about 4 correct digits out of the original 16, so the naive small root is accurate only to roughly 4 significant digits.