Finite Differences
When a derivative is needed but only function values are available, from a black-box simulation, measured data or a grid in a PDE solver, we approximate it by finite differences: combinations of function values at nearby points. This lesson derives the standard formulas from Taylor series and measures their order of accuracy.
The basic formulas
Taylor's theorem gives . Rearranging:
| Formula | Expression | Truncation error |
|---|---|---|
| forward | ||
| backward | ||
| centered | ||
| second derivative |
The centered formula cancels the even-order terms, which gains an order for free.
import numpy as np
f, df, d2f = np.sin, np.cos, lambda x: -np.sin(x)
x = 1.0
print(" h forward centered 2nd deriv")
for h in (0.1, 0.05, 0.025, 0.0125):
fwd = (f(x + h) - f(x)) / h - df(x)
cen = (f(x + h) - f(x - h)) / (2 * h) - df(x)
sec = (f(x + h) - 2 * f(x) + f(x - h)) / h**2 - d2f(x)
print(f"{h:7.4f} {fwd: .3e} {cen: .3e} {sec: .3e}") h forward centered 2nd deriv
0.1000 -4.294e-02 -9.001e-04 7.010e-04
0.0500 -2.126e-02 -2.251e-04 1.753e-04
0.0250 -1.057e-02 -5.628e-05 4.383e-05
0.0125 -5.273e-03 -1.407e-05 1.096e-05
Halving halves the forward error (first order) and quarters the centered errors (second order).
Deriving formulas with more points
Any formula can be found by requiring it to be exact for , which gives a small Vandermonde-like system for the weights. One-sided formulas are needed at boundaries.
import numpy as np
from fractions import Fraction
def fd_weights(offsets, deriv):
"""Weights a_j with f^(deriv)(0) ~ sum a_j f(j h) / h^deriv."""
n = len(offsets)
A = np.array([[o**k for o in offsets] for k in range(n)], dtype=float)
rhs = np.zeros(n); rhs[deriv] = np.prod(range(1, deriv + 1))
return np.linalg.solve(A, rhs)
for offs, d in (([-1, 0, 1], 1), ([0, 1, 2], 1), ([-2, -1, 0, 1, 2], 1), ([-1, 0, 1], 2)):
w = fd_weights(offs, d)
print(f"derivative {d}, offsets {offs}:", [str(Fraction(v).limit_denominator(100)) for v in w])derivative 1, offsets [-1, 0, 1]: ['-1/2', '0', '1/2']
derivative 1, offsets [0, 1, 2]: ['-3/2', '2', '-1/2']
derivative 1, offsets [-2, -1, 0, 1, 2]: ['1/12', '-2/3', '0', '2/3', '-1/12']
derivative 2, offsets [-1, 0, 1]: ['1', '-2', '1']
The second line, , is a second-order one-sided formula used at the boundary of a grid.
Differentiating data on a grid
np.gradient uses centered differences inside the array and second-order one-sided formulas at the ends:
import numpy as np
x = np.linspace(0, 2, 21)
y = x**3
dy = np.gradient(y, x, edge_order=2)
print("max error of np.gradient:", f"{np.max(np.abs(dy - 3 * x**2)):.2e}")
print("error at the ends:", np.round(dy[[0, -1]] - 3 * x[[0, -1]] ** 2, 6))max error of np.gradient: 2.00e-02
error at the ends: [-0.02 -0.02]
For a cubic the centered error is exactly inside the grid, and the one-sided end formulas have twice that error, still second order.
Noisy data
Finite differences amplify noise: an error in the data becomes about in the derivative. For measured data, smooth first (fit a spline or a local polynomial, e.g. the Savitzky-Golay filter) and differentiate the fit. The same effect, with rounding error as the noise, is the subject of Error and Step Size in Finite Differences.
In software
np.gradient,np.diff,scipy.signal.savgol_filter(deriv=1);scipy.optimize.approx_fprimeandscipy.differentiate.derivative(SciPy 1.15+) for functions.- Automatic differentiation (JAX, PyTorch) gives exact derivatives of code and is preferred when available; finite differences remain the standard for gradient checks of AD code.
Exercises
Exercise 1: Apply the formula
Estimate for with the centered difference and . What is the error?
Answer
; error .
Solution
. The predicted error is exact here since .
Exercise 2: Order of a formula
What is the order of as an approximation of ?
Answer
Second order.
Solution
It is the centered difference with step around the point .
Exercise 3: Fourth-order centered formula (code)
Check numerically that is fourth order for at .
Answer
The error ratios for halving are about 16.
Solution
import numpy as np
errs = []
for h in (0.2, 0.1, 0.05, 0.025):
d = (np.exp(-2 * h) - 8 * np.exp(-h) + 8 * np.exp(h) - np.exp(2 * h)) / (12 * h)
errs.append(abs(d - 1))
print(np.round(np.array(errs[:-1]) / np.array(errs[1:]), 2))[16.06 16.01 16. ]
Test yourself
The centered difference has error…
The standard 3-point formula for is…
Why are finite differences of noisy data unreliable?
- They are biased
- Dividing by small amplifies the noise
- They need equal spacing
- They need the exact derivative