Catastrophic Cancellation
Subtracting two nearly equal numbers is exact in floating point, yet it is the most common way to lose accuracy. The difference keeps only the digits in which the operands differ, and any error those operands already carried becomes large relative to the small result. This lesson shows how to spot the problem and rewrite formulas to avoid it.
Why subtraction amplifies errors
Suppose and carry small relative errors. Then
When the factor is huge. If and agree in their first 10 digits, about 10 digits of the difference are lost.
Example: for small
, so for the float is exactly and the difference is , though the true value is . The identity has no subtraction:
import numpy as np
for x in (1e-2, 1e-5, 1e-8):
naive = 1 - np.cos(x)
stable = 2 * np.sin(x / 2) ** 2
print(f"x = {x:.0e}: naive {naive:.15e}, stable {stable:.15e}")x = 1e-02: naive 4.999958333473664e-05, stable 4.999958333472221e-05
x = 1e-05: naive 5.000000413701855e-11, stable 4.999999999958334e-11
x = 1e-08: naive 0.000000000000000e+00, stable 5.000000000000001e-17
Example: the quadratic formula
The roots of are . When , and one of the two signs cancels. The fix: compute the root without cancellation, then get the other one from Vieta's formula .
import numpy as np
a, b, c = 1.0, 1e8, 1.0 # roots near -1e8 and -1e-8
d = np.sqrt(b * b - 4 * a * c)
naive_small = (-b + d) / (2 * a)
big = (-b - np.sign(b) * d) / (2 * a) # same signs: no cancellation
stable_small = c / (a * big)
print(f"naive small root : {naive_small:.16e}")
print(f"stable small root: {stable_small:.16e}")
print("np.roots :", np.roots([a, b, c]))naive small root : -7.4505805969238281e-09
stable small root: -1.0000000000000000e-08
np.roots : [-1.e+08 -1.e-08]
The naive formula gets the small root wrong in the first digit, while the stable version is correct to all digits.
Library functions that avoid cancellation
| Naive | Better | Why |
|---|---|---|
np.log(1 + x) |
np.log1p(x) |
rounds away the low digits of small |
np.exp(x) - 1 |
np.expm1(x) |
for small |
np.sqrt(x*x + y*y) |
np.hypot(x, y) |
avoids overflow and underflow |
x - np.round(x) loops |
np.fmod, np.remainder |
exact remainders |
import numpy as np
x = 1e-10
print("log(1+x):", np.log(1 + x), " log1p:", np.log1p(x))
print("exp(x)-1:", np.exp(x) - 1, " expm1:", np.expm1(x))
with np.errstate(over="ignore"):
naive = np.sqrt(np.float64(3e200) ** 2 + np.float64(4e200) ** 2)
print("sqrt(x*x+y*y):", naive, " hypot:", np.hypot(3e200, 4e200))log(1+x): 1.000000082690371e-10 log1p: 9.999999999500001e-11
exp(x)-1: 1.000000082740371e-10 expm1: 1.00000000005e-10
sqrt(x*x+y*y): inf hypot: 4.9999999999999995e+200
Example: the one-pass variance
The textbook formula subtracts two large, nearly equal numbers when the mean is large compared with the spread. Subtracting the mean first (the two-pass formula, or Welford's online algorithm) avoids it.
import numpy as np
rng = np.random.default_rng(3)
x = 1e8 + rng.normal(0, 1, 10_000) # mean 1e8, variance about 1
one_pass = np.mean(x * x) - np.mean(x) ** 2
two_pass = np.mean((x - np.mean(x)) ** 2)
print(f"one-pass: {one_pass:.6f}")
print(f"two-pass: {two_pass:.6f}")
print(f"np.var : {np.var(x):.6f}")one-pass: 0.000000
two-pass: 1.006857
np.var : 1.006857
In software
np.varandpandas.Series.varsubtract the mean first. Hand-written SQL or streaming code often does not; Welford's update ( plus a running sum of squared deviations) is the standard fix.- Softmax and log-sum-exp subtract the maximum before exponentiating, which avoids overflow (Math for ML).
- Shift data before fitting: polynomial fits in raw years (2020, 2021, …) suffer from cancellation; fitting in does not.
Exercises
Exercise 1: Rewrite
Rewrite for large without cancellation.
Answer
.
Solution
Multiply and divide by the conjugate : the numerator becomes .
Exercise 2: Digits lost
and each have relative error . About how many correct digits does have?
Answer
About 8.
Solution
, and the amplification factor is . The relative error grows to about , so 8 to 9 digits remain.
Exercise 3: near 0 (code)
Compare (np.exp(x) - 1) / x and np.expm1(x) / x for . The exact value is about .
Answer
The naive version is wrong from the 8th significant digit at and by about 11 % at ; expm1 stays correct.
Solution
import numpy as np
for x in (1e-5, 1e-10, 1e-15):
print(f"{x:.0e}: naive {(np.exp(x) - 1) / x:.15f}, expm1 {np.expm1(x) / x:.15f}")1e-05: naive 1.000005000006965, expm1 1.000005000016667
1e-10: naive 1.000000082740371, expm1 1.000000000050000
1e-15: naive 1.110223024625157, expm1 1.000000000000001
Test yourself
Which operation can turn tiny relative errors into large ones?
- Multiplying two numbers
- Subtracting two nearly equal numbers
- Dividing by 2
- Adding two positive numbers
To compute for you should use…
np.log(1 + x)np.log1p(x)np.log(x) + 1np.exp(x)
When is the quadratic formula inaccurate?
- When , for the root with and of opposite signs
- Never
- When
- When the roots are complex