Rounding Error and Its Propagation
Each floating-point operation commits a relative error of at most . That is tiny, but long computations perform millions of operations, and some operations magnify the errors already present. This lesson measures how rounding errors accumulate in sums and how to keep them small.
Error of one operation
With , , a sum of numbers computed left to right satisfies, to first order,
This is a worst-case bound. Rounding errors usually have random signs and partly cancel, so the typical error grows more like .
Accumulating a sum
Adding ten million times shows the effect: the exact answer is , and the naive loop loses several digits. NumPy's sum uses pairwise summation (adding in a balanced tree), whose error bound grows like instead of . Python's math.fsum tracks the lost low-order bits and returns the correctly rounded sum.
import math
import numpy as np
n = 10_000_000
x = np.full(n, 0.1)
naive = 0.0
for v in x[:1_000_000]: # loop over the first million only (speed)
naive += v
print(f"naive loop, 1e6 terms : {naive:.10f} (error {abs(naive - 1e5):.2e})")
print(f"np.sum, 1e7 terms : {np.sum(x):.10f} (error {abs(np.sum(x) - 1e6):.2e})")
print(f"math.fsum, 1e7 terms : {math.fsum(x):.10f}")
print(f"np.cumsum last value : {np.cumsum(x)[-1]:.10f} (sequential, error {abs(np.cumsum(x)[-1] - 1e6):.2e})")naive loop, 1e6 terms : 100000.0000013329 (error 1.33e-06)
np.sum, 1e7 terms : 999999.9999999782 (error 2.18e-08)
math.fsum, 1e7 terms : 1000000.0000000000
np.cumsum last value : 999999.9998389754 (sequential, error 1.61e-04)
math.fsum gives to all printed digits (the remaining difference is just that itself is not exactly in binary). np.cumsum is sequential by nature, so it shows the naive error growth.
Kahan's compensated summation
Kahan's algorithm keeps a running compensation holding the part of each addend that was rounded away, and feeds it back into the next addition:
import numpy as np
def kahan_sum(xs):
s, c = 0.0, 0.0
for x in xs:
y = x - c # corrected next term
t = s + y # low bits of y are lost here...
c = (t - s) - y # ...and recovered here
s = t
return s
rng = np.random.default_rng(7)
x = rng.uniform(0, 1, 200_000)
exact = __import__("math").fsum(x)
naive = 0.0
for v in x:
naive += v
print(f"naive error : {abs(naive - exact):.2e}")
print(f"kahan error : {abs(kahan_sum(x) - exact):.2e}")
print(f"np.sum error: {abs(np.sum(x) - exact):.2e}")naive error : 4.80e-10
kahan error : 0.00e+00
np.sum error: 1.46e-11
Order matters
Floating-point addition is not associative: may differ from . Adding small numbers to a huge one loses them; adding the small ones together first keeps them. Summing a convergent series from the smallest term up is usually more accurate. The example uses single precision so the effect is large enough to see:
import numpy as np
a, b, c = 1e16, 1.0, 1.0
print((a + b) + c, a + (b + c))
terms = 1.0 / np.arange(1, 1_000_001, dtype=np.float32) ** 2 # single precision
reference = np.sum(terms.astype(np.float64))
forward = np.cumsum(terms)[-1] # sequential, largest term first
backward = np.cumsum(terms[::-1])[-1] # sequential, smallest term first
print(f"float32 sum of 1/k^2, largest first : error {abs(forward - reference):.2e}")
print(f"float32 sum of 1/k^2, smallest first: error {abs(backward - reference):.2e}")1e+16 1.0000000000000002e+16
float32 sum of 1/k^2, largest first : error 2.08e-04
float32 sum of 1/k^2, smallest first: error 8.10e-08
Growth through multiplication
Products and quotients are kinder: relative errors simply add, so a product of factors has relative error at most about . Trouble comes from subtraction of nearly equal numbers (Catastrophic Cancellation) and from problems that are sensitive in themselves (Conditioning of Problems).
In software
- Parallel and GPU reductions add numbers in a different order on each run or hardware, so results differ in the last bits. Reproducible-sum libraries and
math.fsumexist for when that matters. - Accumulate in higher precision when you can: summing
float32data into afloat64accumulator (np.sum(x, dtype=np.float64)) is a cheap fix.
Exercises
Exercise 1: Error bound
Bound the error of naively summing positive numbers whose exact sum is .
Answer
About .
Solution
. The typical error is much smaller, around .
Exercise 2: Associativity
Find the values of (0.1 + 0.2) + 0.3 and 0.1 + (0.2 + 0.3) and explain the difference.
Answer
0.6000000000000001 and 0.6.
Solution
rounds to , and adding rounds up again; happens to round to exactly the float nearest , and rounds to the float nearest .
Exercise 3: float32 accumulation (code)
Sum one million copies of np.float32(0.1) with np.cumsum in float32 and with a float64 accumulator. Compare the results with .
Answer
The float32 running sum is off by about ; the float64 accumulator is right to about 7 digits (limited by in float32).
Solution
import numpy as np
x = np.full(1_000_000, 0.1, dtype=np.float32)
print(float(np.cumsum(x)[-1]))
print(float(np.cumsum(x, dtype=np.float64)[-1]))100958.34375
100000.00149011612
Each float32 addition near has absolute rounding error up to , and a million of them add up.
Test yourself
Why is np.sum usually more accurate than a Python loop?
- It uses higher precision
- It uses pairwise summation, whose error grows like
- It sorts the data first
- It is not more accurate
Is floating-point addition associative?
- Yes
- No
- Only for integers stored as floats
- Only in NumPy
What does Kahan summation keep track of?
- The largest term
- The low-order bits lost in each addition
- The number of terms
- The exact rational sum