Approximation Error
Every number a program computes from a series, a step size or a sum is an approximation. This lesson shows how to bound the error of a Taylor polynomial, how many terms to keep, and why making a step smaller can make a result worse once floating-point rounding joins in.
Two kinds of error
| Error | Comes from | Shrinks when | Example |
|---|---|---|---|
| Truncation error | cutting an infinite process short (a series, a limit, a step size) | you take more terms or a smaller step | using 5 terms of the series for |
| Rounding error | storing numbers in finite precision (64-bit floats keep about 16 significant digits) | you use more precision, or reorganise the formula | 0.1 + 0.2 != 0.3 |
Mathematics deals with the first, computer arithmetic adds the second, and in real code you must balance them.
Taylor's remainder
The Taylor polynomial of degree at leaves a remainder . Taylor's theorem (Lagrange form) says that for some between and :
We do not know , but if on the interval, we get a guaranteed bound:
The in the denominator grows so fast that a few terms are enough near . For an alternating series with shrinking terms, the simpler rule from Convergence Tests applies: the error is at most the first omitted term.
Choosing the number of terms
How many terms of give with error below ? Every derivative of is on , so :
import math
target = 1e-10
n = 0
while 3 / math.factorial(n + 1) >= target: # bound M·1^(n+1)/(n+1)!
n += 1
approx = sum(1 / math.factorial(k) for k in range(n + 1))
print("degree needed:", n)
print(f"bound {3 / math.factorial(n + 1):.2e}")
print(f"actual {abs(approx - math.e):.2e}")degree needed: 13
bound 3.44e-11
actual 1.23e-11
The real error is below the bound, as it must be. The bound is cautious (we used instead of the smallest possible value), which is the usual price of a guarantee.
When smaller is worse: the finite-difference trap
The derivative approximation has truncation error about , which shrinks with . But the subtraction loses digits when the two numbers are almost equal (catastrophic cancellation). The rounding error is about with , which grows as shrinks.
import math
import matplotlib.pyplot as plt
x, exact = 1.0, math.cos(1.0) # d/dx sin x = cos x
hs = [10.0 ** -k for k in range(1, 16)]
errors = [abs((math.sin(x + h) - math.sin(x)) / h - exact) for h in hs]
for h, err in zip(hs, errors):
if h in (1e-1, 1e-4, 1e-8, 1e-12, 1e-15):
print(f"h = {h:.0e}: error {err:.2e}")
best = min(zip(errors, hs))
print(f"best h = {best[1]:.0e}, error {best[0]:.2e}")
plt.figure(figsize=(6, 4))
plt.loglog(hs, errors, "o-")
plt.xlabel("step h")
plt.ylabel("error of the derivative")
plt.title("Truncation (right) vs rounding (left)")h = 1e-01: error 4.29e-02
h = 1e-04: error 4.21e-05
h = 1e-08: error 2.97e-09
h = 1e-12: error 4.32e-05
h = 1e-15: error 1.48e-02
best h = 1e-08, error 2.97e-09
The total error is V-shaped on a log-log plot. The best step is near , where the two errors are about equal, and the best accuracy is only about 8 digits, not 16. This is why automatic differentiation (see Automatic Differentiation) is preferred over finite differences when training neural networks.
Rewriting a formula to avoid cancellation
Sometimes algebra removes the rounding problem. tends to as , but near 0 it subtracts two nearly equal numbers. The identity computes the same value without the subtraction:
import math
for x in [1e-3, 1e-6, 1e-8]:
naive = (1 - math.cos(x)) / x**2
stable = 2 * math.sin(x / 2) ** 2 / x**2
print(f"x = {x:.0e}: naive {naive:.10f} stable {stable:.10f}")
values = [0.1] * 10
total = 0.0
for v in values: # plain running sum
total += v
print("running total =", total)
print("math.fsum(values) =", math.fsum(values))x = 1e-03: naive 0.4999999583 stable 0.4999999583
x = 1e-06: naive 0.5000444503 stable 0.5000000000
x = 1e-08: naive 0.0000000000 stable 0.5000000000
running total = 0.9999999999999999
math.fsum(values) = 1.0
math.fsum tracks the rounding error of each addition and corrects for it. Since Python 3.12 the built-in sum also compensates for float rounding, and NumPy's sum uses pairwise summation for a similar reason; a hand-written += loop (in any language) does neither. Library functions like math.expm1(x) () and math.log1p(x) () exist because the naive formulas cancel catastrophically for small .
Tip: A practical recipe: pick a method whose truncation error you can bound, choose the number of terms or the step so that bound meets your tolerance, and keep the tolerance well above , where rounding takes over.
Exercises
Exercise 1: Bound a sine approximation
Bound the error of .
Answer
At most (the actual error is about too).
Solution
is also the degree-4 Taylor polynomial (the coefficient is 0), so use . All derivatives of are bounded by :
The series is also alternating, giving the same bound: the first omitted term .
import math
print(f"{abs(math.sin(0.5) - (0.5 - 0.5**3 / 6)):.3e} bound {0.5**5 / 120:.3e}")2.589e-04 bound 2.604e-04
Exercise 2: Alternating bound
You approximate by . What is the largest the error can be?
Answer
Solution
The series at alternates with decreasing terms, so the error is at most the first omitted term, .
Exercise 3: Terms for
How many terms (highest degree ) of the series for guarantee an error below at ? Use .
Answer
Degree (15 terms).
Solution
We need .
import math
n = 0
while 7.4 * 2 ** (n + 1) / math.factorial(n + 1) >= 1e-6:
n += 1
approx = sum(2**k / math.factorial(k) for k in range(n + 1))
print(n, f"{abs(approx - math.exp(2)):.2e}")14 2.86e-08
Exercise 4: The best step for central differences
The central difference has truncation error proportional to . Find the best power-of-ten for at , and compare it with .
Answer
The best is around to , with an error near , better than the forward difference's best of about .
Solution
Truncation , rounding : they balance near .
import math
errs = []
for k in range(1, 13):
h = 10.0 ** -k
d = (math.sin(1 + h) - math.sin(1 - h)) / (2 * h)
errs.append((abs(d - math.cos(1)), h))
err, h = min(errs)
print(f"best h = {h:.0e}, error {err:.1e}")best h = 1e-05, error 1.1e-11
Test yourself
Making the step in smaller and smaller in floating point eventually…
- gives the exact derivative
- makes the result worse, because rounding error grows like
- has no effect
- makes the truncation error grow
In the Lagrange remainder bound , what is ?
- The number of terms
- The largest value of on the interval
- A bound on between and
- Machine epsilon
Which is a truncation error?
- 0.1 + 0.2 printing 0.30000000000000004
- Stopping the series for after 6 terms
- Losing digits in
- Integer overflow