Numerical Calculus and Floating Point
On paper a derivative is a limit as . On a computer cannot go to zero, every number carries a relative rounding error of about , and subtracting two nearly equal numbers can wipe out every correct digit. This lesson analyses the error of finite differences, shows how to choose the step size, removes catastrophic cancellation by rewriting formulas, introduces the complex-step derivative, and explains why a perfectly convergent ODE method can blow up when its step is too large.
Background: Linear Approximations and Differentials, Applications of Taylor Polynomials, Approximate Integration and Direction Fields and Euler's Method. The survey course has Numerical ODE methods; a full treatment is planned in Numerical Methods.
Floating point in one table
A 64-bit float stores about 16 significant decimal digits. The machine epsilon is the gap between 1 and the next float, and every arithmetic operation is exact up to a relative error of at most .
| Effect | Example | Consequence |
|---|---|---|
| Rounding | never test floats with == | |
| Cancellation | in floats, true value | relative error can become 100 % |
| Absorption | small terms vanish in large sums | |
| Overflow | rescale (e.g. subtract the max in softmax) |
Finite differences and the best step size
Taylor's theorem gives the truncation error of the two basic difference quotients:
Rounding adds a second error: and are each off by about , and dividing their difference by magnifies that to about . The total error of the forward difference is therefore roughly
For the central difference the same balance gives and a best error near . Smaller is worse, not better.
import numpy as np
import matplotlib.pyplot as plt
f, df, x = np.sin, np.cos, 1.0
hs = 10.0 ** -np.arange(1, 16)
fwd = np.abs((f(x + hs) - f(x)) / hs - df(x))
cen = np.abs((f(x + hs) - f(x - hs)) / (2*hs) - df(x))
for h, a, b in zip(hs[::2], fwd[::2], cen[::2]):
print(f"h = {h:.0e} forward error {a:.1e} central error {b:.1e}")
print("best h: forward", f"{hs[np.argmin(fwd)]:.0e}", " central", f"{hs[np.argmin(cen)]:.0e}")
plt.figure(figsize=(6, 4))
plt.loglog(hs, fwd, "o-", label="forward")
plt.loglog(hs, cen, "s-", label="central")
plt.xlabel("step h"); plt.ylabel("|error|"); plt.legend(); plt.grid(True, which="both", lw=0.3)h = 1e-01 forward error 4.3e-02 central error 9.0e-04
h = 1e-03 forward error 4.2e-04 central error 9.0e-08
h = 1e-05 forward error 4.2e-06 central error 1.1e-11
h = 1e-07 forward error 4.2e-08 central error 1.9e-10
h = 1e-09 forward error 5.3e-08 central error 3.0e-09
h = 1e-11 forward error 1.2e-06 central error 1.2e-06
h = 1e-13 forward error 7.3e-04 central error 1.8e-04
h = 1e-15 forward error 1.5e-02 central error 1.5e-02
best h: forward 1e-08 central 1e-05
The V shape is the whole story: on the right, truncation error falls with slope 1 (forward) or 2 (central); on the left, rounding error rises with slope .
Removing cancellation, and the complex step
Cancellation is fixed by algebra, not by more precision. Rewrite the formula so that it no longer subtracts nearly equal quantities:
| Unstable | Stable equivalent |
|---|---|
| (small ) | |
| (large ) | |
| (small ) | math.expm1(x) |
| (small ) | math.log1p(x) |
| when |
The complex-step derivative avoids the subtraction in a difference quotient completely. For a real-analytic , Taylor expansion with an imaginary step gives , so
import math, cmath
x = 1e-8
print("1 - cos x :", 1 - math.cos(x))
print("2 sin^2(x/2) :", 2 * math.sin(x / 2)**2)
print("exp(x) - 1 :", math.exp(x) - 1)
print("expm1(x) :", math.expm1(x))
f = lambda z: cmath.exp(z) / cmath.sqrt(z**3 + 1) # works for real and complex input
x0 = 1.5
exact = math.exp(x0) / math.sqrt(x0**3 + 1) * (1 - 1.5 * x0**2 / (x0**3 + 1))
central = (f(x0 + 1e-6) - f(x0 - 1e-6)).real / 2e-6
complex_step = f(complex(x0, 1e-200)).imag / 1e-200
print(f"central error : {abs(central - exact):.1e}")
print(f"complex-step error : {abs(complex_step - exact):.1e}")1 - cos x : 0.0
2 sin^2(x/2) : 5.0000000000000005e-17
exp(x) - 1 : 9.99999993922529e-09
expm1(x) : 1.0000000050000001e-08
central error : 8.3e-11
complex-step error : 5.6e-17
Stability of ODE solvers
Convergence ( as ) is not enough; the method must also be stable for the you actually use. Test it on (), whose solution decays. One explicit Euler step multiplies by , one implicit (backward) Euler step by :
A stiff system contains a fast-decaying component (large ) next to slow ones; explicit methods are then forced to use tiny steps even after the fast part has died out. Game physics meets this with stiff springs, which is why engines use semi-implicit or implicit integrators.
lam, T = 50.0, 1.0 # explicit Euler needs h <= 2/50 = 0.04
for h in [0.01, 0.03, 0.05]:
y_exp = y_imp = 1.0
for _ in range(round(T / h)):
y_exp *= (1 - h * lam)
y_imp /= (1 + h * lam)
print(f"h = {h}: factor {1 - h*lam:+.1f} explicit y(1) = {y_exp: .3e} implicit y(1) = {y_imp:.3e}")
print("exact y(1) =", f"{2.718281828459045 ** -50:.3e}")h = 0.01: factor +0.5 explicit y(1) = 7.889e-31 implicit y(1) = 2.460e-18
h = 0.03: factor -0.5 explicit y(1) = -1.164e-10 implicit y(1) = 7.379e-14
h = 0.05: factor -1.5 explicit y(1) = 3.325e+03 implicit y(1) = 1.314e-11
exact y(1) = 1.929e-22
At the explicit solution already flips sign every step, and at it explodes to 3325 instead of decaying. Implicit Euler stays bounded at every step size, though at large it is stable without being accurate: stability keeps the error from growing, and accuracy still needs small steps.
In software
- Gradient checks in ML code compare backprop with central differences; use to in float64 and much larger in float32, where (see Calculus for Machine Learning).
- Numerically stable library functions such as
log1p,expm1,hypot,logsumexpexist exactly to avoid the cancellations above. - Physics engines fix the time step and use semi-implicit Euler or Verlet because explicit Euler gains energy and explodes with stiff springs. Circuit simulators (SPICE) and chemistry codes use implicit methods for stiff equations.
Exercises
Exercise 1: The best central step
Using the error model with and , find the that minimises and the size of the minimum error.
Answer
, minimum error .
Solution
Exercise 2: A stability limit
Explicit Euler is used on . What is the largest step size for which the numerical solution does not grow?
Answer
.
Solution
Each step multiplies by . The condition means . At the factor is exactly (an oscillation that neither grows nor decays).
Exercise 3: Fix the cancellation (code)
Evaluate for both directly and with the stable form, and compare with the true value .
Answer
The direct formula gives 5.000038072466850e-07 (only about 5 correct digits); the stable form gives 4.999999999998749e-07 (correct to the last digit).
Solution
Multiply and divide by the conjugate: , so the difference equals , which has no subtraction.
import math
x = 1e12
print(f"{math.sqrt(x + 1) - math.sqrt(x):.15e}")
print(f"{1 / (math.sqrt(x + 1) + math.sqrt(x)):.15e}")5.000038072466850e-07
4.999999999998749e-07
Exercise 4: A complex-step derivative (code)
Find for by hand and with the complex-step formula using .
Answer
; .
Solution
import math, cmath
f = lambda z: z * cmath.exp(cmath.sin(z))
print(round(f(complex(2, 1e-30)).imag / 1e-30, 6))
print(round(math.exp(math.sin(2)) * (1 + 2 * math.cos(2)), 6))0.416344
0.416344
Test yourself
Why does the error of grow again when becomes very small?
- Truncation error grows
- Rounding errors in are divided by a tiny
- The derivative changes
- Python limits the number of digits
Which expression computes accurately for ?
- math.exp(x) - 1
- math.expm1(x)
- math.log(x) + 1
- (math.exp(2*x) - 1) / 2
Explicit Euler on with step is stable when…
- always