TExcelTAD
Home › Numerical Methods › Catastrophic Cancellation

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 a~=a(1+δa)\tilde{a} = a(1 + \delta_a) and b~=b(1+δb)\tilde{b} = b(1 + \delta_b) carry small relative errors. Then

∣(a~−b~)−(a−b)∣∣a−b∣≤∣a∣+∣b∣∣a−b∣ max⁡(∣δa∣,∣δb∣).\frac{\lvert(\tilde{a} - \tilde{b}) - (a - b)\rvert}{\lvert a - b\rvert} \le \frac{\lvert a\rvert + \lvert b\rvert}{\lvert a - b\rvert}\,\max(\lvert\delta_a\rvert, \lvert\delta_b\rvert).

When a≈ba \approx b the factor ∣a∣+∣b∣∣a−b∣\frac{\lvert a\rvert + \lvert b\rvert}{\lvert a - b\rvert} is huge. If aa and bb agree in their first 10 digits, about 10 digits of the difference are lost.

Example: 1−cos⁡x1 - \cos x for small xx

cos⁡x≈1−x2/2\cos x \approx 1 - x^2/2, so for x=10−8x = 10^{-8} the float cos⁡x\cos x is exactly 11 and the difference is 00, though the true value is 5×10−175 \times 10^{-17}. The identity 1−cos⁡x=2sin⁡2(x/2)1 - \cos x = 2\sin^2(x/2) has no subtraction:

python · try it yourself
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 ax2+bx+c=0ax^2 + bx + c = 0 are −b±b2−4ac2a\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}. When b2≫4acb^2 \gg 4ac, b2−4ac≈∣b∣\sqrt{b^2 - 4ac} \approx \lvert b\rvert and one of the two signs cancels. The fix: compute the root without cancellation, then get the other one from Vieta's formula x1x2=c/ax_1x_2 = c/a.

python · try it yourself
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) 1+x1 + x rounds away the low digits of small xx
np.exp(x) - 1 np.expm1(x) ex≈1e^x \approx 1 for small xx
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
python · try it yourself
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 var⁡=x2‾−xˉ2\operatorname{var} = \overline{x^2} - \bar{x}^2 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.

python · try it yourself
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.var and pandas.Series.var subtract the mean first. Hand-written SQL or streaming code often does not; Welford's update (Mk=Mk−1+(xk−Mk−1)/kM_k = M_{k-1} + (x_k - M_{k-1})/k 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 t−2020t - 2020 does not.

Exercises

Exercise 1: Rewrite

Rewrite x+1−x\sqrt{x + 1} - \sqrt{x} for large xx without cancellation.

Answer

1x+1+x\dfrac{1}{\sqrt{x + 1} + \sqrt{x}}.

Solution

Multiply and divide by the conjugate x+1+x\sqrt{x + 1} + \sqrt{x}: the numerator becomes (x+1)−x=1(x + 1) - x = 1.

Exercise 2: Digits lost

a=1.23456789012a = 1.23456789012 and b=1.23456780000b = 1.23456780000 each have relative error 10−1610^{-16}. About how many correct digits does a−ba - b have?

Answer

About 8.

Solution

a−b≈9×10−8a - b \approx 9 \times 10^{-8}, and the amplification factor is ∣a∣+∣b∣∣a−b∣≈2.7×107\frac{\lvert a\rvert + \lvert b\rvert}{\lvert a - b\rvert} \approx 2.7 \times 10^7. The relative error grows to about 3×10−93 \times 10^{-9}, so 8 to 9 digits remain.

Exercise 3: (ex−1)/x(e^x - 1)/x near 0 (code)

Compare (np.exp(x) - 1) / x and np.expm1(x) / x for x=10−5,10−10,10−15x = 10^{-5}, 10^{-10}, 10^{-15}. The exact value is about 1+x/21 + x/2.

Answer

The naive version is wrong from the 8th significant digit at x=10−10x = 10^{-10} and by about 11 % at x=10−15x = 10^{-15}; expm1 stays correct.

Solution
python · try it yourself
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?

  1. Multiplying two numbers
  2. Subtracting two nearly equal numbers
  3. Dividing by 2
  4. Adding two positive numbers

To compute ln⁡(1+x)\ln(1 + x) for x=10−12x = 10^{-12} you should use…

  1. np.log(1 + x)
  2. np.log1p(x)
  3. np.log(x) + 1
  4. np.exp(x)

When is the quadratic formula inaccurate?

  1. When b2≫∣4ac∣b^2 \gg \lvert 4ac\rvert, for the root with −b-b and ±⋅\pm\sqrt{\cdot} of opposite signs
  2. Never
  3. When a=1a = 1
  4. When the roots are complex