TExcelTAD
Home › Calculus in Depth › Numerical Calculus and Floating Point

Numerical Calculus and Floating Point

On paper a derivative is a limit as h→0h \to 0. On a computer hh cannot go to zero, every number carries a relative rounding error of about 10−1610^{-16}, 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 ε=2−52≈2.2×10−16\varepsilon = 2^{-52} \approx 2.2 \times 10^{-16} is the gap between 1 and the next float, and every arithmetic operation is exact up to a relative error of at most ε/2\varepsilon/2.

Effect Example Consequence
Rounding 0.1+0.2=0.300000000000000040.1 + 0.2 = 0.30000000000000004 never test floats with ==
Cancellation 1−cos⁡(10−8)=01 - \cos(10^{-8}) = 0 in floats, true value 5×10−175 \times 10^{-17} relative error can become 100 %
Absorption 1016+1=101610^{16} + 1 = 10^{16} small terms vanish in large sums
Overflow e1000=infe^{1000} = \text{inf} 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:

forward:f(x+h)−f(x)h=f′(x)+h2⋅f′′(ξ)error O(h)central:f(x+h)−f(x−h)2h=f′(x)+h26⋅f′′′(ξ)error O(h2)\begin{aligned} &\text{forward:} & \frac{f(x + h) - f(x)}{h} &= f'(x) + \frac{h}{2} \cdot f''(\xi) && \text{error } O(h) \\ &\text{central:} & \frac{f(x + h) - f(x - h)}{2h} &= f'(x) + \frac{h^2}{6} \cdot f'''(\xi) && \text{error } O(h^2) \end{aligned}

Rounding adds a second error: f(x+h)f(x + h) and f(x)f(x) are each off by about ε⋅∣f∣\varepsilon \cdot \lvert f \rvert, and dividing their difference by hh magnifies that to about ε⋅∣f∣/h\varepsilon \cdot \lvert f \rvert / h. The total error of the forward difference is therefore roughly

E(h)≈h2⋅∣f′′∣+ε⋅∣f∣hminimised ath∗≈2ε⋅∣f∣∣f′′∣≈ε≈10−8E(h) \approx \frac{h}{2} \cdot \lvert f'' \rvert + \frac{\varepsilon \cdot \lvert f \rvert}{h} \qquad \text{minimised at} \quad h^* \approx \sqrt{\frac{2\varepsilon \cdot \lvert f \rvert}{\lvert f'' \rvert}} \approx \sqrt{\varepsilon} \approx 10^{-8}

For the central difference the same balance gives h∗≈ε3≈6×10−6h^* \approx \sqrt[3]{\varepsilon} \approx 6 \times 10^{-6} and a best error near ε2/3≈10−11\varepsilon^{2/3} \approx 10^{-11}. Smaller hh is worse, not better.

python · try it yourself
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 −1-1.

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
1−cos⁡x1 - \cos x (small xx) 2⋅sin⁡2(x/2)2 \cdot \sin^2(x/2)
x+1−x\sqrt{x + 1} - \sqrt{x} (large xx) 1x+1+x\frac{1}{\sqrt{x + 1} + \sqrt{x}}
ex−1e^x - 1 (small xx) math.expm1(x)
ln⁡(1+x)\ln(1 + x) (small xx) math.log1p(x)
−b+b2−4ac2a\frac{-b + \sqrt{b^2 - 4ac}}{2a} when b>0b > 0 2c−b−b2−4ac\frac{2c}{-b - \sqrt{b^2 - 4ac}}

The complex-step derivative avoids the subtraction in a difference quotient completely. For a real-analytic ff, Taylor expansion with an imaginary step gives f(x+ih)=f(x)+ih⋅f′(x)−h22f′′(x)−⋯f(x + ih) = f(x) + ih \cdot f'(x) - \frac{h^2}{2}f''(x) - \cdots, so

f′(x)=Im⁡f(x+ih)h+O(h2)(no subtraction, so h can be 10−200)f'(x) = \frac{\operatorname{Im} f(x + ih)}{h} + O(h^2) \qquad (\text{no subtraction, so } h \text{ can be } 10^{-200})
python · try it yourself
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 (error→0\text{error} \to 0 as h→0h \to 0) is not enough; the method must also be stable for the hh you actually use. Test it on y′=−λyy' = -\lambda y (λ>0\lambda > 0), whose solution e−λte^{-\lambda t} decays. One explicit Euler step multiplies yy by (1−hλ)(1 - h\lambda), one implicit (backward) Euler step by 1/(1+hλ)1/(1 + h\lambda):

explicit Euler is stable  ⟺  ∣1−hλ∣≤1  ⟺  h≤2/λimplicit Euler is stable for every h>0\begin{aligned} &\text{explicit Euler is stable} \iff \lvert 1 - h\lambda \rvert \le 1 \iff h \le 2/\lambda \\ &\text{implicit Euler is stable for every } h > 0 \end{aligned}

A stiff system contains a fast-decaying component (large λ\lambda) 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.

python · try it yourself
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 h=0.03h = 0.03 the explicit solution already flips sign every step, and at h=0.05h = 0.05 it explodes to 3325 instead of decaying. Implicit Euler stays bounded at every step size, though at large hh 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 h≈10−5h \approx 10^{-5} to 10−610^{-6} in float64 and much larger in float32, where ε≈1.2×10−7\varepsilon \approx 1.2 \times 10^{-7} (see Calculus for Machine Learning).
  • Numerically stable library functions such as log1p, expm1, hypot, logsumexp exist 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 E(h)≈h26⋅∣f′′′∣+ε⋅∣f∣/hE(h) \approx \frac{h^2}{6} \cdot \lvert f''' \rvert + \varepsilon \cdot \lvert f \rvert / h with ∣f∣≈∣f′′′∣≈1\lvert f \rvert \approx \lvert f''' \rvert \approx 1 and ε=2.2×10−16\varepsilon = 2.2 \times 10^{-16}, find the hh that minimises EE and the size of the minimum error.

Answer

h∗=3ε3≈8.7×10−6h^* = \sqrt[3]{3\varepsilon} \approx 8.7 \times 10^{-6}, minimum error ≈3.8×10−11\approx 3.8 \times 10^{-11}.

Solution
E′(h)=h3−εh2=0  →  h3=3ε=6.6×10−16  →  h≈8.7×10−6E(h∗)=h∗26+εh∗≈1.26×10−11+2.53×10−11≈3.8×10−11\begin{aligned} E'(h) &= \frac{h}{3} - \frac{\varepsilon}{h^2} = 0 \;\to\; h^3 = 3\varepsilon = 6.6 \times 10^{-16} \;\to\; h \approx 8.7 \times 10^{-6} \\ E(h^*) &= \frac{{h^*}^2}{6} + \frac{\varepsilon}{h^*} \approx 1.26 \times 10^{-11} + 2.53 \times 10^{-11} \approx 3.8 \times 10^{-11} \end{aligned}

Exercise 2: A stability limit

Explicit Euler is used on y′=−200yy' = -200y. What is the largest step size for which the numerical solution does not grow?

Answer

h=2/200=0.01h = 2/200 = 0.01.

Solution

Each step multiplies yy by 1−200h1 - 200h. The condition ∣1−200h∣≤1\lvert 1 - 200h \rvert \le 1 means 0≤h≤0.010 \le h \le 0.01. At h=0.01h = 0.01 the factor is exactly −1-1 (an oscillation that neither grows nor decays).

Exercise 3: Fix the cancellation (code)

Evaluate x+1−x\sqrt{x + 1} - \sqrt{x} for x=1012x = 10^{12} both directly and with the stable form, and compare with the true value ≈12x=5×10−7\approx \frac{1}{2\sqrt{x}} = 5 \times 10^{-7}.

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: (x+1−x)(x+1+x)=1(\sqrt{x + 1} - \sqrt{x})(\sqrt{x + 1} + \sqrt{x}) = 1, so the difference equals 1x+1+x\frac{1}{\sqrt{x + 1} + \sqrt{x}}, which has no subtraction.

python · try it yourself
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 f′(2)f'(2) for f(x)=x⋅esin⁡xf(x) = x \cdot e^{\sin x} by hand and with the complex-step formula using h=10−30h = 10^{-30}.

Answer

f′(x)=esin⁡x⋅(1+x⋅cos⁡x)f'(x) = e^{\sin x} \cdot (1 + x \cdot \cos x); f′(2)≈0.416344f'(2) \approx 0.416344.

Solution
f′=esin⁡x+x⋅cos⁡x⋅esin⁡x=esin⁡x(1+xcos⁡x)f′(2)=e0.909297⋅(1+2⋅(−0.416147))≈2.482578⋅0.167706≈0.416344\begin{aligned} f' &= e^{\sin x} + x \cdot \cos x \cdot e^{\sin x} = e^{\sin x}(1 + x\cos x) \\ f'(2) &= e^{0.909297} \cdot (1 + 2 \cdot (-0.416147)) \approx 2.482578 \cdot 0.167706 \approx 0.416344 \end{aligned}
python · try it yourself
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 f(x+h)−f(x)h\frac{f(x + h) - f(x)}{h} grow again when hh becomes very small?

  1. Truncation error grows
  2. Rounding errors in f(x+h)−f(x)f(x + h) - f(x) are divided by a tiny hh
  3. The derivative changes
  4. Python limits the number of digits

Which expression computes ex−1e^x - 1 accurately for x=10−12x = 10^{-12}?

  1. math.exp(x) - 1
  2. math.expm1(x)
  3. math.log(x) + 1
  4. (math.exp(2*x) - 1) / 2

Explicit Euler on y′=−λyy' = -\lambda y with step hh is stable when…

  1. h≤2/λh \le 2/\lambda
  2. h≤λ/2h \le \lambda/2
  3. always
  4. h≥1/λh \ge 1/\lambda