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 metres with an error of metre.
Sensor B reads metres with an error of metre. Which reading is more accurate relative to its size?
A: sensor A
Its relative error is , against 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 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 ticks without adding anything tick by tick:
you know the counter 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 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 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 ); .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 times.
The error of accumulated grows at least as fast as , 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 is itself inexact, and this representation error, about , stays.
In the three runs of the output it is smaller than half the gap near , so the final rounding returns exactly the stored number of 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 and a small , the difference is about (because the derivative of is and ), but the formula subtracts two nearly equal numbers, both close to .
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 gets small, then rewrite the difference in stable.
Hint
The identity for a difference of sines: . Substitute and .
Python in this task. It asks you to rewrite one formula inside a function.math.cos(x) is (the angle in radians), math.sin(x) is 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 ).
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 and we get .
In the naive version each of the two sines is stored with a rounding error of about relative to itself, and the difference between them is very small, so the relative error in the difference grows as gets smaller:
in the output it is about for , for and for (about two more digits at each step).
Rounding also contributes: the grid of stored numbers near 1 is , so for only about two digits of remain.
In the product formula nothing is subtracted: is computed for small without losing digits, and the relative error stays at about 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 .
- a. We approximate by with , in exact arithmetic.
- b. We add a million times in binary64 and get instead of .
- c. We store in binary32 and get .
- d. We add from to in binary64 and get . The exact value of the infinite sum is .
- e. We add the same sum in binary32 and get . Up to which 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 in binary64 and in binary32. In a series that is stopped, the deviation is the sum of all the omitted terms.
Hint for part a
From calculus:
The first omitted term is .
Hint for part d
Step by step: the omitted terms are . For every ,
because the denominator is smaller than . So we can replace each omitted term by the larger difference, and the sum “telescopes”:
In each bracket the negative term cancels the positive term in the next bracket, and only the first remains.
So the truncation is smaller than .
Solution
-
a. Truncation. The arithmetic is exact, and the deviation comes from the terms that were left out.
The first of them is , and this is also the actual deviation (). -
b. Round-off. The stored value of is not exact, and every addition rounds again.
After a million additions the deviation is , andmath.fsumgives because it rounds once, at the end. -
c. Round-off. is not stored exactly, and the stored value is off by , a relative error of , smaller than half the machine epsilon of binary32 ().
-
d. Truncation. The computed sum is smaller than : 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 4They differ in the sixth digit after the point, against .
The digits after it are identical, which is misleading:
the difference is , about one millionth, and it is far larger than the round-off error of binary64 (about near , and about 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 , but the next million, from to , add up to about (half of the whole tail), and the whole tail is about .
Each term is small, but there are very many more and they accumulate.
In the series of it is different: decays fast, and the tail is almost equal to the next term (). -
e. Round-off. The deviation is far larger than the truncation of ():
the sum gets stuck, and the cause is round-off. The gap near in binary32 is , and once the term is smaller than half a gap, , adding it does not change the stored sum.
At the term is exactly half a gap (a tie), and the first at which the sum does not change is .
So it is worth adding terms up to about . The stuck sum, , is not the exact partial sum:
it is higher by 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 is of a similar size, , while the deviation from is .
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 meters, and the target moves at meters per second.
The value is stored chopped to 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 .
Chopping to bits leaves an error below .
Solution
- a. The number of ticks is . The requirement is , so seconds per tick.
- b. We need . is too large, and 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 seconds per tick and a shift of about meters, within the meters.
c. Choosing a representation format. A tracking system follows an object that moves at meters per second.
It counts 100 ticks per second and computes time as seconds.
It runs 24 hours in a row, that is, ticks, and the value is stored in one representation format.
-
- The window is meter. Which of the formats binary16, binary32 and binary64 are enough?
-
- What if the window is centimeter?
Hint
Find the stored value of 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 is the error per tick, and the deviation is .
A format is enough when the deviation does not exceed the half-width of the window.
Solution
| Format | Stored value of | Error per tick (seconds) | Deviation (meters) |
|---|---|---|---|
| binary16 | |||
| binary32 | |||
| binary64 | (the stored value differs from it by ) |
The deviation is . In part 1 (a window of 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 meter): binary32 is not enough, because , 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 is equivalent to . 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 and the true variance is . In the second form we square before subtracting:
the squares are near , the gap between stored numbers there is , and the subtraction returns only rounding errors, here .
In the first form we subtract first, while the numbers are still stored exactly:
the deviations are , the squares , and their mean .
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 liters at each pulse to a variable total.
When total reaches liters, that is, after pulses, the controller closes the valve.
The value 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.0notTrue, although after 100,000 pulses of liters there are exactly 30,000 liters? - b. Why is
abs_tol=1e-18not suitable? And why isabs_tol=0.5not suitable? - c. Which values of
abs_tolare 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 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 , every addition rounds, and the errors accumulate: in this run
at_fulldiffers from by about liters (it is short). This is far larger than the gap between stored numbers near (), soat_fullis not the stored number of and the equality fails. The valve would never close. - b. 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). is larger than , 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 liters (measured), and smaller than . Any value between and fits, for example , and the output shows that it gives
Trueonly 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 is negligible.”
Why this is wrong
The reasoning looks at one operation. The Patriot’s relative error was , 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 , 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
- With the stored value of this lesson, what is the window shift after 12 hours of operation?
- 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 ( s). By how much is the computed distance off?
- 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.
- In Python,
(1 + 1e-16) - 1gives0.0, although the mathematical answer is . 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 ?
Solutions
- 12 hours are ticks, so the clock error is seconds and the shift is about metres.
- The distance error is the speed times the time error: 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.)
- The absolute errors are equal, 1 metre. The relative errors are and : the second measurement is 10,000 times worse in relative terms.
- Near 1 neighbouring binary64 numbers are apart. The number 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.