TExcelTAD
Home › Numerical Methods › Rounding Error and Machine Epsilon

Rounding Error and Its Propagation

Each floating-point operation commits a relative error of at most u≈1.1×10−16u \approx 1.1 \times 10^{-16}. 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 fl⁡(a+b)=(a+b)(1+δ)\operatorname{fl}(a + b) = (a + b)(1 + \delta), ∣δ∣≤u\lvert\delta\rvert \le u, a sum of nn numbers computed left to right satisfies, to first order,

∣s^n−sn∣≲(n−1) u∑i=1n∣xi∣.\lvert\hat{s}_n - s_n\rvert \lesssim (n - 1)\,u \sum_{i=1}^{n}\lvert x_i\rvert.

This is a worst-case bound. Rounding errors usually have random signs and partly cancel, so the typical error grows more like n u\sqrt{n}\,u.

Accumulating a sum

Adding 0.10.1 ten million times shows the effect: the exact answer is 10610^6, and the naive loop loses several digits. NumPy's sum uses pairwise summation (adding in a balanced tree), whose error bound grows like log⁡2n\log_2 n instead of nn. Python's math.fsum tracks the lost low-order bits and returns the correctly rounded sum.

python · try it yourself
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 10610^6 to all printed digits (the remaining difference is just that 0.10.1 itself is not exactly 110\frac{1}{10} 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 cc holding the part of each addend that was rounded away, and feeds it back into the next addition:

python · try it yourself
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: (a+b)+c(a + b) + c may differ from a+(b+c)a + (b + c). 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:

python · try it yourself
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 nn factors has relative error at most about nunu. 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.fsum exist for when that matters.
  • Accumulate in higher precision when you can: summing float32 data into a float64 accumulator (np.sum(x, dtype=np.float64)) is a cheap fix.

Exercises

Exercise 1: Error bound

Bound the error of naively summing 10610^6 positive numbers whose exact sum is 11.

Answer

About 106⋅1.1×10−16≈1.1×10−1010^6 \cdot 1.1 \times 10^{-16} \approx 1.1 \times 10^{-10}.

Solution

(n−1)u∑∣xi∣≈106⋅1.1×10−16⋅1(n - 1)u\sum\lvert x_i\rvert \approx 10^6 \cdot 1.1 \times 10^{-16} \cdot 1. The typical error is much smaller, around n u≈10−13\sqrt{n}\,u \approx 10^{-13}.

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

0.1+0.20.1 + 0.2 rounds to 0.300000000000000040.30000000000000004, and adding 0.30.3 rounds up again; 0.2+0.30.2 + 0.3 happens to round to exactly the float nearest 0.50.5, and 0.1+0.50.1 + 0.5 rounds to the float nearest 0.60.6.

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 100000100000.

Answer

The float32 running sum is off by about 10310^3; the float64 accumulator is right to about 7 digits (limited by 0.10.1 in float32).

Solution
python · try it yourself
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 10510^5 has absolute rounding error up to ≈0.004\approx 0.004, and a million of them add up.

Test yourself

Why is np.sum usually more accurate than a Python loop?

  1. It uses higher precision
  2. It uses pairwise summation, whose error grows like log⁡n\log n
  3. It sorts the data first
  4. It is not more accurate

Is floating-point addition associative?

  1. Yes
  2. No
  3. Only for integers stored as floats
  4. Only in NumPy

What does Kahan summation keep track of?

  1. The largest term
  2. The low-order bits lost in each addition
  3. The number of terms
  4. The exact rational sum