Skip to content

Finite differences: numerical derivatives

5 min read

Short answer

Forward: f′(x)≈f(x+h)−f(x)hf'(x)\approx\dfrac{f(x+h)-f(x)}{h} (error O(h)O(h)). Central: f′(x)≈f(x+h)−f(x−h)2hf'(x)\approx\dfrac{f(x+h)-f(x-h)}{2h} (error O(h2)O(h^2)). Central differences are far more accurate for the same hh, but making hh too small amplifies round-off error.

Bar chartForwardCentralAbsolute error for sin x at x = 1 with h = 0.1.
Symmetric sampling cancels the leading error term.

Where the errors come from

Taylor: f(x+h)=f(x)+hf′+h22f′′+h36f′′′+⋯f(x+h)=f(x)+hf'+\tfrac{h^2}2f''+\tfrac{h^3}6f'''+\cdots. Solving for f′f' in the forward formula leaves −h2f′′-\tfrac h2f'' as the error. In the central formula the h2h^2 terms cancel, leaving −h26f′′′-\tfrac{h^2}6f'''.

The round-off trap

Truncation error falls as hh shrinks, but subtracting nearly equal numbers loses digits, so round-off error grows like ε/h\varepsilon/h. The total error is smallest at an intermediate hh (about 10−810^{-8} for forward differences in double precision).

Worked example

Estimate f′(1)f'(1) for f(x)=sin⁡xf(x)=\sin x with h=0.1h=0.1 using forward and central differences. The exact value is cos⁡1=0.5403\cos1=0.5403.

sin⁡1=0.84147\sin1=0.84147, sin⁡1.1=0.89121\sin1.1=0.89121, sin⁡0.9=0.78333\sin0.9=0.78333. Forward: 0.89121−0.841470.1=0.4974\dfrac{0.89121-0.84147}{0.1}=0.4974 (error 0.0430.043). Central: 0.89121−0.783330.2=0.5394\dfrac{0.89121-0.78333}{0.2}=0.5394 (error 0.00090.0009).

Try it yourself

What second-derivative formula uses f(x−h)f(x-h), f(x)f(x) and f(x+h)f(x+h)?

Show the answer

f′′(x)≈f(x+h)−2f(x)+f(x−h)h2f''(x)\approx\dfrac{f(x+h)-2f(x)+f(x-h)}{h^2} (second-order accurate).

Keep going with practice

Vidi's differential-equation lessons use finite differences to turn PDEs into solvable linear systems.