TExcelTAD
Home › Numerical Methods › Finite-Difference Derivatives

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 f(x+h)=f(x)+hf′(x)+h22f′′(x)+h36f′′′(x)+⋯f(x + h) = f(x) + hf'(x) + \frac{h^2}{2}f''(x) + \frac{h^3}{6}f'''(x) + \cdots. Rearranging:

Formula Expression Truncation error
forward f(x+h)−f(x)h\dfrac{f(x + h) - f(x)}{h} −h2f′′(x)+O(h2)-\frac{h}{2}f''(x) + O(h^2)
backward f(x)−f(x−h)h\dfrac{f(x) - f(x - h)}{h} h2f′′(x)+O(h2)\frac{h}{2}f''(x) + O(h^2)
centered f(x+h)−f(x−h)2h\dfrac{f(x + h) - f(x - h)}{2h} −h26f′′′(x)+O(h4)-\frac{h^2}{6}f'''(x) + O(h^4)
second derivative f(x+h)−2f(x)+f(x−h)h2\dfrac{f(x + h) - 2f(x) + f(x - h)}{h^2} −h212f(4)(x)+O(h4)-\frac{h^2}{12}f^{(4)}(x) + O(h^4)

The centered formula cancels the even-order terms, which gains an order for free.

python · try it yourself
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 hh halves the forward error (first order) and quarters the centered errors (second order).

Deriving formulas with more points

Any formula f′(x)≈1h∑jajf(x+jh)f'(x) \approx \frac{1}{h}\sum_j a_jf(x + jh) can be found by requiring it to be exact for 1,x,x2,…1, x, x^2, \ldots, which gives a small Vandermonde-like system for the weights. One-sided formulas are needed at boundaries.

python · try it yourself
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, −3f(x)+4f(x+h)−f(x+2h)2h\frac{-3f(x) + 4f(x + h) - f(x + 2h)}{2h}, 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:

python · try it yourself
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 h26f′′′=h2=0.01\frac{h^2}{6}f''' = h^2 = 0.01 inside the grid, and the one-sided end formulas have twice that error, still second order.

Noisy data

Finite differences amplify noise: an error δ\delta in the data becomes about δh\frac{\delta}{h} 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_fprime and scipy.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 f′(2)f'(2) for f(x)=x3f(x) = x^3 with the centered difference and h=0.1h = 0.1. What is the error?

Answer

12.0112.01; error 0.010.01.

Solution

2.13−1.930.2=9.261−6.8590.2=12.01\frac{2.1^3 - 1.9^3}{0.2} = \frac{9.261 - 6.859}{0.2} = 12.01. The predicted error h26f′′′=0.016⋅6=0.01\frac{h^2}{6}f''' = \frac{0.01}{6}\cdot 6 = 0.01 is exact here since f(5)=0f^{(5)} = 0.

Exercise 2: Order of a formula

What is the order of f(x+2h)−f(x)2h\frac{f(x + 2h) - f(x)}{2h} as an approximation of f′(x+h)f'(x + h)?

Answer

Second order.

Solution

It is the centered difference with step hh around the point x+hx + h.

Exercise 3: Fourth-order centered formula (code)

Check numerically that f(x−2h)−8f(x−h)+8f(x+h)−f(x+2h)12h\frac{f(x - 2h) - 8f(x - h) + 8f(x + h) - f(x + 2h)}{12h} is fourth order for f=exf = e^x at x=0x = 0.

Answer

The error ratios for halving hh are about 16.

Solution
python · try it yourself
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 f(x+h)−f(x−h)2h\frac{f(x + h) - f(x - h)}{2h} has error…

  1. O(h)O(h)
  2. O(h2)O(h^2)
  3. O(h3)O(h^3)
  4. O(1)O(1)

The standard 3-point formula for f′′(x)f''(x) is…

  1. f(x+h)−f(x)h2\frac{f(x + h) - f(x)}{h^2}
  2. f(x+h)−2f(x)+f(x−h)h2\frac{f(x + h) - 2f(x) + f(x - h)}{h^2}
  3. f(x+h)−f(x−h)2h\frac{f(x + h) - f(x - h)}{2h}
  4. f(x+2h)−f(x)h2\frac{f(x + 2h) - f(x)}{h^2}

Why are finite differences of noisy data unreliable?

  1. They are biased
  2. Dividing by small hh amplifies the noise
  3. They need equal spacing
  4. They need the exact derivative