Exercise

Practice: error, accumulation and subtraction of nearly equal numbers

Absolute and relative error, avoiding accumulated drift and rewriting a formula that subtracts nearly equal numbers, the usual mistakes and transfer questions: practice for the lecture on the Patriot clock and numerical error.

Last updated:


On this practice page we practice how to:

  • choose between absolute and relative error for a given situation;
  • remove accumulated drift by changing how a quantity is computed;
  • rewrite a formula so that nearly equal numbers are not subtracted;
  • tell truncation error from round-off error and estimate their size;
  • decide the precision a system needs and change the order of operations to reduce round-off error;
  • avoid the usual mistakes about numerical error.

This practice follows the lecture Small Errors, Big Consequences: The Patriot Clock:
read it or attend it first.

Warm-up: absolute or relative?

1. Sensor A reads 10001000 metres with an error of 11 metre.
Sensor B reads 1010 metres with an error of 0.50.5 metre. Which reading is more accurate relative to its size?

A: sensor A

Its relative error is 11000=0.1%\frac1{1000}=0.1\%⁠‏, against 0.510=5%\frac{0.5}{10}=5\% for sensor B. A larger absolute error can be a much smaller relative error.

B: sensor B, because its absolute error is smaller

The absolute error is smaller, but it is large compared with a reading of 10 metres.
Relative error compares the error with the size of the number.

C: they are equally accurate

Only the absolute errors differ by a factor of 2; the relative errors differ by a factor of 50.

D: there is no way to tell without a third sensor

The two readings and errors are enough: divide each error by its reading.

Accumulation in code: avoid the drift

The lecture added 0.10.1 ten times and ended below 1.0. Here you measure how the error grows with the number of additions, and then remove it.
The function from_counter should return the time after nn ticks without adding anything tick by tick:
you know the counter nn is an integer. Press Run, then fix the TODO and run again.

Python in this task. It asks you to write one line. for _ in range(n) repeats nn times; t += 0.1 adds 0.1 to t; abs(...) is the absolute value; math.fsum adds a list of numbers and rounds once, at the end; [0.1] * n is a list of nn copies of 0.1; f"..." is a text with values inserted into the braces.
After a colon inside the braces we write how to display the value:
<6 pads it with spaces on the right to a width of 6 characters, so that the columns line up; .2e writes a number in scientific notation with two digits after the point (1.11e-16 means 1.11×10−161.11\times10^{-16}⁠); .0e does the same with no digits after the point.

import math

def accumulated(n):
    """The time after n ticks of 0.1, adding tick by tick."""
    t = 0.0
    for _ in range(n):
        t += 0.1
    return t

def from_counter(n):
    """The same time without accumulating anything."""
    # TODO: compute it from the integer n directly
    return 0.0

for n in (10, 1000, 100000):
    exact = n / 10
    print(
        f"n={n:<6} accumulated error "
        f"{abs(accumulated(n) - exact):.2e}   "
        f"from the counter "
        f"{abs(from_counter(n) - exact):.0e}   "
        f"fsum error {abs(math.fsum([0.1] * n) - exact):.0e}"
    )
n=10     accumulated error 1.11e-16   from the counter 0e+00   fsum error 0e+00
n=1000   accumulated error 1.41e-12   from the counter 0e+00   fsum error 0e+00
n=100000 accumulated error 1.88e-08   from the counter 0e+00   fsum error 0e+00
Solution

Replace the TODO line by return n / 10. One division of an exact integer by 10 rounds once, instead of nn times.
The error of accumulated grows at least as fast as nn⁠, and in the output above even faster (from 1000 to 100 000 additions it grows about 13 000 times), because every addition rounds a larger and larger sum; this is the same kind of accumulation as in the Patriot, in a rounding version rather than a truncating one.
math.fsum also removes the drift that builds up in the additions:
it adds the stored values exactly and rounds only once, at the end.
The stored value of 0.10.1 is itself inexact, and this representation error, about n⋅5.55×10−18n\cdot5.55\times10^{-18}⁠, stays.
In the three runs of the output it is smaller than half the gap near n/10n/10⁠, so the final rounding returns exactly the stored number of n/10n/10 and the error is 0.
In a real clock the better design is to store the tick count and convert it to seconds only when needed.

When subtraction wipes out digits, rewrite the formula

For x=1x=1 and a small hh⁠, the difference sin⁡(x+h)−sin⁡x\sin(x+h)-\sin x is about 0.5403 h0.5403\,h (because the derivative of sin⁡\sin is cos⁡\cos and cos⁡1≈0.5403\cos1\approx0.5403⁠), but the formula subtracts two nearly equal numbers, both close to 0.840.84⁠.
State in words before you open the block: how can the difference be written as a product, so that nearly equal numbers are not subtracted?
Run it and see how the naive result loses digits as hh gets small, then rewrite the difference in stable.

Hint

The identity for a difference of sines: sin⁡A−sin⁡B=2cos⁡A+B2 sin⁡A−B2\sin A-\sin B=2\cos\dfrac{A+B}{2}\,\sin\dfrac{A-B}{2}⁠. Substitute A=x+hA=x+h and B=xB=x⁠.

Python in this task. It asks you to rewrite one formula inside a function.
math.cos(x) is cos⁡x\cos x (the angle in radians), math.sin(x) is sin⁡x\sin x in the same way, and h:<7 pads to a width of 7 as <6 did.
Here :.10e writes a number in scientific notation with ten digits after the point (5.4e-11 means 5.4×10−115.4\times10^{-11}⁠).

import math

def naive(x, h):
    return math.sin(x + h) - math.sin(x)

def stable(x, h):
    # TODO: rewrite the difference as a product, so that no two
    # nearly equal numbers are subtracted
    return naive(x, h)

for h in (1e-10, 1e-12, 1e-14):
    print(
        f"h={h:<7} naive {naive(1.0, h):.10e}   "
        f"stable {stable(1.0, h):.10e}"
    )
h=1e-10   naive 5.4030224739e-11   stable 5.4030230583e-11
h=1e-12   naive 5.4034554609e-13   stable 5.4030230587e-13
h=1e-14   naive 5.4400928207e-15   stable 5.4030230587e-15
Solution

Replace the TODO line with this line:

return 2 * math.cos(x + h / 2) * math.sin(h / 2)

This is the same expression: from the identity for a difference of sines with A=x+hA=x+h and B=xB=x we get sin⁡(x+h)−sin⁡x=2cos⁡ ⁣(x+h2)sin⁡h2\sin(x+h)-\sin x=2\cos\!\left(x+\tfrac h2\right)\sin\tfrac h2⁠.
In the naive version each of the two sines is stored with a rounding error of about 10−1610^{-16} relative to itself, and the difference between them is very small, so the relative error in the difference grows as hh gets smaller:
in the output it is about 1.1×10−71.1\times10^{-7} for h=10−10h=10^{-10}⁠, 8.0×10−58.0\times10^{-5} for h=10−12h=10^{-12} and 6.9×10−36.9\times10^{-3} for h=10−14h=10^{-14} (about two more digits at each step).
Rounding x+hx+h also contributes: the grid of stored numbers near 1 is 2.2×10−162.2\times10^{-16}⁠, so for h=10−14h=10^{-14} only about two digits of hh remain.
In the product formula nothing is subtracted: sin⁡h2\sin\frac h2 is computed for small hh without losing digits, and the relative error stays at about 10−1610^{-16} in all three cases.

Practice: the kind of error and planning the computation

1. Which error is this? In each situation decide whether the deviation is a truncation error or a round-off error, and estimate its size.
Items d and e concern the series ∑k=1∞1k2=1+14+19+116+⋯=π26=1.6449340668482264…\sum_{k=1}^{\infty}\frac1{k^2}=1+\frac14+\frac19+\frac1{16}+\cdots=\dfrac{\pi^2}{6}=1.6449340668482264\ldots⁠.

  • a. We approximate sin⁡0.1\sin 0.1 by x−x36x-\dfrac{x^3}{6} with x=0.1x=0.1⁠, in exact arithmetic.
  • b. We add 0.010.01 a million times in binary64 and get 10000.00000017185610000.000000171856 instead of 1000010000⁠.
  • c. We store 13\tfrac13 in binary32 and get 0.33333334326744080.3333333432674408⁠.
  • d. We add 1k2\dfrac1{k^2} from k=1k=1 to N=106N=10^{6} in binary64 and get 1.644933066848771.64493306684877⁠. The exact value of the infinite sum is π26≈1.644934066848\dfrac{\pi^2}{6}\approx1.644934066848⁠.
  • e. We add the same sum in binary32 and get 1.64472531.6447253⁠. Up to which NN is it worth adding terms in binary32?
Hint

A truncation error remains even in perfectly exact arithmetic, and a round-off error comes from the finite number of bits.
Compare the size of the deviation with the gap between stored numbers:
near 1 it is 2−52≈2.2×10−162^{-52}\approx2.2\times10^{-16} in binary64 and 2−23≈1.2×10−72^{-23}\approx1.2\times10^{-7} in binary32. In a series that is stopped, the deviation is the sum of all the omitted terms.

Hint for part a

From calculus:

sin⁡x=∑k=0∞(−1)kx2k+1(2k+1)!=x−x33!+x55!−⋯\sin x=\sum_{k=0}^{\infty}(-1)^k\frac{x^{2k+1}}{(2k+1)!}=x-\frac{x^3}{3!}+\frac{x^5}{5!}-\cdots

The first omitted term is x55!\dfrac{x^5}{5!}⁠.

Hint for part d

Step by step: the omitted terms are 1(N+1)2+1(N+2)2+⋯\dfrac1{(N+1)^2}+\dfrac1{(N+2)^2}+\cdots⁠. For every k≥2k\ge2⁠,

1k−1−1k=k−(k−1)k(k−1)=1k(k−1)>1k2\frac1{k-1}-\frac1k=\frac{k-(k-1)}{k(k-1)}=\frac1{k(k-1)}>\frac1{k^2}

because the denominator k(k−1)k(k-1) is smaller than k2k^2⁠. So we can replace each omitted term by the larger difference, and the sum “telescopes”:

∑k=N+1∞1k2<(1N−1N+1)+(1N+1−1N+2)+(1N+2−1N+3)+⋯=1N\sum_{k=N+1}^{\infty}\frac1{k^2}<\left(\frac1N-\frac1{N+1}\right)+\left(\frac1{N+1}-\frac1{N+2}\right)+\left(\frac1{N+2}-\frac1{N+3}\right)+\cdots=\frac1N

In each bracket the negative term cancels the positive term in the next bracket, and only the first 1N\dfrac1N remains.
So the truncation is smaller than 1N=10−6\dfrac1N=10^{-6}⁠.

Solution
  • a. Truncation. The arithmetic is exact, and the deviation comes from the terms that were left out.
    The first of them is x5120=8.3×10−8\dfrac{x^5}{120}=8.3\times10^{-8}⁠, and this is also the actual deviation (8.33×10−88.33\times10^{-8}⁠).

  • b. Round-off. The stored value of 0.010.01 is not exact, and every addition rounds again.
    After a million additions the deviation is 1.7×10−71.7\times10^{-7}⁠, and math.fsum gives 10000.010000.0 because it rounds once, at the end.

  • c. Round-off. 13\tfrac13 is not stored exactly, and the stored value is off by 9.9×10−99.9\times10^{-9}⁠, a relative error of 3.0×10−83.0\times10^{-8}⁠, smaller than half the machine epsilon of binary32 (2−24≈6×10−82^{-24}\approx6\times10^{-8}⁠).

  • d. Truncation. The computed sum is smaller than π26\dfrac{\pi^2}{6}⁠: we add only positive terms and stop, so every partial sum lies below the infinite sum.
    Here are the two numbers one above the other, aligned by the decimal point:

    computed sum: 1.644933 06684877
    pi^2/6:       1.644934 06684823
                         ^ the sixth digit after the point: 3 against 4

    They differ in the sixth digit after the point, 33 against 44⁠.
    The digits 0668406684 after it are identical, which is misleading:
    the difference is 0.99999946×10−60.99999946\times10^{-6}⁠, about one millionth, and it is far larger than the round-off error of binary64 (about 10−1610^{-16} near 1.61.6⁠, and about 4.4×10−144.4\times10^{-14} over a million additions).

    The difference is not the next term but the sum of all the terms we did not add.
    The last term we added is 1N2=10−12\dfrac1{N^2}=10^{-12}⁠, but the next million, from k=N+1k=N+1 to 2N2N⁠, add up to about 5×10−75\times10^{-7} (half of the whole tail), and the whole tail is about 9.99999×10−7≈1N9.99999\times10^{-7}\approx\dfrac1N⁠.
    Each term is small, but there are very many more and they accumulate.
    In the series of ee it is different: 1k!\dfrac1{k!} decays fast, and the tail is almost equal to the next term (120!≈4×10−19\dfrac1{20!}\approx4\times10^{-19}⁠).

  • e. Round-off. The deviation 2.1×10−42.1\times10^{-4} is far larger than the truncation of N=106N=10^{6} (10−610^{-6}⁠):
    the sum gets stuck, and the cause is round-off. The gap near 1.641.64 in binary32 is 2−23≈1.2×10−72^{-23}\approx1.2\times10^{-7}⁠, and once the term 1k2\dfrac1{k^2} is smaller than half a gap, 6×10−86\times10^{-8}⁠, adding it does not change the stored sum.
    At k=4096k=4096 the term is exactly half a gap (a tie), and the first kk at which the sum does not change is 40974097⁠.
    So it is worth adding terms up to about N=4096N=4096⁠. The stuck sum, 1.64472532271.6447253227⁠, is not the exact partial sum:
    it is higher by 3.5×10−53.5\times10^{-5} than the exact sum of the first 4096 terms, and that excess is round-off.
    By coincidence, at the same point the truncation error of stopping at 40964096 is of a similar size, 2.4×10−42.4\times10^{-4}⁠, while the deviation from π26\dfrac{\pi^2}{6} is 2.09×10−42.09\times10^{-4}⁠.

2. How many bits are enough? A radar battery runs 24 hours in a row, and its clock advances 10 ticks per second.
The radar intercepts as long as the window shift does not exceed 5050 meters, and the target moves at 15001500 meters per second.
The value 0.10.1 is stored chopped to pp fractional bits, and time is counted from switch-on.

  • a. What is the largest error per tick that is allowed?
  • b. What is the smallest number of bits that the formula guarantees will be enough?
Hint

The shift is the speed times the number of ticks times the error per tick, and it must be at most 5050⁠.
Chopping to pp bits leaves an error below 2−p2^{-p}⁠.

Solution
  • a. The number of ticks is 24⋅3600⋅10=864,00024\cdot3600\cdot10=864{,}000⁠. The requirement is 1500⋅864,000⋅e≤501500\cdot864{,}000\cdot e\le50⁠, so e≤501500⋅864,000≈3.86×10−8e\le\dfrac{50}{1500\cdot864{,}000}\approx3.86\times10^{-8} seconds per tick.
  • b. We need 2−p≤3.86×10−82^{-p}\le3.86\times10^{-8}⁠. 2−24≈5.96×10−82^{-24}\approx5.96\times10^{-8} is too large, and 2−25≈2.98×10−82^{-25}\approx2.98\times10^{-8} fits. So 25 bits guarantee an intercept. The bound is a sufficient condition, not a necessary one: 25 bits guarantee an intercept, and fewer bits may be enough, but the bound does not guarantee that. For example, 24 bits give an error of 3.58×10−83.58\times10^{-8} seconds per tick and a shift of about 1500⋅864,000⋅3.58×10−8≈461500\cdot864{,}000\cdot3.58\times10^{-8}\approx46 meters, within the 5050 meters.

c. Choosing a representation format. A tracking system follows an object that moves at v=300v=300 meters per second.
It counts 100 ticks per second and computes time as number of ticks×0.01\text{number of ticks}\times0.01 seconds.
It runs 24 hours in a row, that is, N=24⋅3600⋅100=8,640,000N=24\cdot3600\cdot100=8{,}640{,}000 ticks, and the value 0.010.01 is stored in one representation format.

    1. The window is ±1\pm1 meter. Which of the formats binary16, binary32 and binary64 are enough?
    1. What if the window is ±1\pm1 centimeter?
Hint

Find the stored value of 0.010.01 in each format, for example in the lab “What did the computer store?” or in code that you write and run.
The difference between the stored value and 0.010.01 is the error per tick, and the deviation is v⋅N⋅errorv\cdot N\cdot\text{error}⁠.
A format is enough when the deviation does not exceed the half-width of the window.

Solution
FormatStored value of 0.010.01Error per tick (seconds)Deviation (meters)
binary160.010002136230468750.010002136230468752.14×10−62.14\times10^{-6}5.54×1035.54\times10^{3}
binary320.0099999997764825820.0099999997764825822.24×10−102.24\times10^{-10}0.5790.579
binary640.010.01 (the stored value differs from it by 2.1×10−192.1\times10^{-19}⁠)2.08×10−192.08\times10^{-19}5.40×10−105.40\times10^{-10}

The deviation is 300⋅8,640,000⋅error300\cdot8{,}640{,}000\cdot\text{error}⁠. In part 1 (a window of 11 meter):
binary16 is not enough, with a deviation of more than 5 kilometers, while binary32 and binary64 are enough.
In part 2 (a window of 0.010.01 meter): binary32 is not enough, because 0.579>0.010.579>0.01⁠, and only binary64 is.

3. Variance without losing the digits. We are given a list of large values close to each other.
The variance formula σ2=1n∑i=1n(xi−μ)2\sigma^2=\frac1n\sum_{i=1}^{n}(x_i-\mu)^2 is equivalent to 1n∑i=1nxi2−μ2\frac1n\sum_{i=1}^{n}x_i^2-\mu^2⁠. Run the code and see what the second form gives, then compute the first form in the TODO line.

data = [3e9 + 1, 3e9 + 2, 3e9 + 3, 3e9 + 6]
n = len(data)
mean = sum(data) / n
naive = sum(x * x for x in data) / n - mean ** 2
# TODO: compute the variance by subtracting the mean first
better = naive
print(naive, better)
0.0 3.5
Solution

Replace the TODO line with better = sum((x - mean) ** 2 for x in data) / n.
The mean is μ=3,000,000,003\mu=3{,}000{,}000{,}003 and the true variance is 3.53.5⁠. In the second form we square before subtracting:
the squares are near 9×10189\times10^{18}⁠, the gap between stored numbers there is 10241024⁠, and the subtraction returns only rounding errors, here 0.00.0⁠.
In the first form we subtract first, while the numbers are still stored exactly:
the deviations are −2,−1,0,3-2,-1,0,3⁠, the squares 4,1,0,94,1,0,9⁠, and their mean 144=3.5\tfrac{14}{4}=3.5⁠.
The order of operations is what makes the difference, and the algebra is the same.

4. A flow controller: a comparison threshold. A flow sensor in a water facility adds 0.30.3 liters at each pulse to a variable total.
When total reaches 3000030000 liters, that is, after 100,000100{,}000 pulses, the controller closes the valve.
The value 0.30.3 is stored in binary64. In the code, rel_tol=0 cancels the relative threshold so that only abs_tol decides.
Run it and read the output.

import math

def total_after(n):
    """The total after n pulses of 0.3 liters, adding pulse by pulse."""
    total = 0.0
    for _ in range(n):
        total += 0.3
    return total

pulses = 100000                    # 30000 liters
at_full, before = total_after(pulses), total_after(pulses - 1)
print(at_full == 30000.0)          # False
for tol in (1e-18, 1e-3, 0.5):
    print(
        f"abs_tol={tol:<6} closes at pulse {pulses}: "
        f"{math.isclose(at_full, 30000.0, rel_tol=0, abs_tol=tol)}   "
        f"at pulse {pulses - 1}: "
        f"{math.isclose(before, 30000.0, rel_tol=0, abs_tol=tol)}"
    )
False
abs_tol=1e-18  closes at pulse 100000: False   at pulse 99999: False
abs_tol=0.001  closes at pulse 100000: True   at pulse 99999: False
abs_tol=0.5    closes at pulse 100000: True   at pulse 99999: True
  • a. Why is at_full == 30000.0 not True, although after 100,000 pulses of 0.30.3 liters there are exactly 30,000 liters?
  • b. Why is abs_tol=1e-18 not suitable? And why is abs_tol=0.5 not suitable?
  • c. Which values of abs_tol are suitable? Give a range and explain.
  • d. How can the controller be designed so that no threshold is needed?
Hint

The deviation of at_full from 3000030000 can be measured by adding a print of at_full - 30000.0.
Every threshold has two requirements: it must include that deviation, and it must not include the previous pulse, which before represents.

Solution
  • a. After 100,000 additions of the stored value of 0.30.3⁠, every addition rounds, and the errors accumulate: in this run at_full differs from 3000030000 by about 4.9×10−84.9\times10^{-8} liters (it is short). This is far larger than the gap between stored numbers near 3000030000 (3.6×10−123.6\times10^{-12}⁠), so at_full is not the stored number of 3000030000 and the equality fails. The valve would never close.
  • b. 10−1810^{-18} is smaller than the deviation, so the check fails even at the right pulse (the same problem as ==: a threshold smaller than the gap near the numbers is equivalent to demanding exact equality). 0.50.5 is larger than 0.30.3⁠, the distance between adjacent pulses, so the check also holds at pulse 99,999 and the valve closes one pulse early.
  • c. The threshold must be larger than the deviation at pulse 100,000, about 4.9×10−84.9\times10^{-8} liters (measured), and smaller than 0.30.3⁠. Any value between 10−710^{-7} and 0.10.1 fits, for example 10−310^{-3}⁠, and the output shows that it gives True only at pulse 100,000.
  • d. Count pulses as an integer: pulses == 100000. Integers are stored exactly, so there is no deviation and no threshold. Convert to liters only when needed.

Common mistakes

“A relative error of 10−610^{-6} is negligible.”

Why this is wrong

The reasoning looks at one operation. The Patriot’s relative error was 9.54×10−79.54\times10^{-7}⁠, and it still produced almost 700 metres, because the error repeated 3.6 million times and was multiplied by about 2,000 metres per second.
Always ask how many times the error repeats and what it is multiplied by.

“Errors cancel on average, so accumulation is harmless.”

Why this is wrong

Cancellation on average needs errors with random signs. Here the same value is stored every time and always falls on the same side of 0.10.1⁠, so every tick adds the same positive error and the total grows linearly.
Even rounding to nearest only reduced the shift to 172 metres, a quarter, not to zero.

“To fix it, just add more bits.”

Why this is incomplete

More bits helps, but not by a rule you can see from the digits:
24 bits chopped is still worse than 23 bits rounded in the simulator, and the right number depends on the window.
Changing the algorithm, counting from the last detection, removed the drift with the same 23 bits.

Transfer practice

  1. With the stored value of this lesson, what is the window shift after 12 hours of operation?
  2. A satellite-navigation receiver measures its distance to a satellite from the travel time of a radio signal, which moves at 299,792,458 metres per second. Its clock is off by one microsecond (10−610^{-6} s). By how much is the computed distance off?
  3. A measurement of 20,000 metres is wrong by 1 metre and a measurement of 2 metres is wrong by 1 metre. Compare the absolute and the relative errors.
  4. In Python, (1 + 1e-16) - 1 gives 0.0, although the mathematical answer is 10−1610^{-16}⁠. Explain with Rounding and Machine Epsilon.
Hint for question 4

How far apart are the stored numbers near 1? Which stored number is nearest to 1+10−161+10^{-16}⁠?

Solutions
  1. 12 hours are 432,000432{,}000 ticks, so the clock error is 432,000×9.54×10−8≈0.0412432{,}000\times9.54\times10^{-8}\approx0.0412 seconds and the shift is about 0.0412×2000≈820.0412\times2000\approx82 metres.
  2. The distance error is the speed times the time error: 299,792,458×10−6≈300299{,}792{,}458\times10^{-6}\approx300 metres. (The receiver finds its position from three unknowns, plus a fourth: its own clock error. This is why satellite navigation measures the distance to four satellites and corrects the receiver’s clock.)
  3. The absolute errors are equal, 1 metre. The relative errors are 120000=5×10−5\frac1{20000}=5\times10^{-5} and 12=0.5\frac12=0.5⁠: the second measurement is 10,000 times worse in relative terms.
  4. Near 1 neighbouring binary64 numbers are 2.2×10−162.2\times10^{-16} apart. The number 1+10−161+10^{-16} is less than half a gap above 1, so it is stored as exactly 1, and subtracting 1 gives 0. The whole answer was lost in the first rounding, before the subtraction.

Continue learning

Then try the questions of Unit 1 to solve on paper. Back to the lecture Small Errors, Big Consequences: The Patriot Clock; the terms are in the glossary.