TExcelTAD
Home › MATLAB / Octave › Numerical Differentiation

Numerical Differentiation

A derivative is a rate of change: velocity from position, slope of a curve, the flow of heat down a temperature gradient. When you only have samples of a function, or a function too awkward to differentiate by hand, you approximate the derivative with finite differences. It looks easy, but it's one of the few places in numerics where taking a smaller step can make the answer worse. This lesson shows why and how to choose well.

Tool What it does Output length
diff(y) Differences y(k+1) - y(k) n − 1
diff(y, 2) Second differences n − 2
gradient(y, h) Central differences inside, one-sided at the ends, divided by the spacing n
[gx, gy] = gradient(Z, hx, hy) Partial derivatives on a 2-D grid same as Z
polyder(p) Exact derivative of a polynomial (Polynomials)
diff(sym) Exact derivative of a formula (Symbolic Math)

diff and gradient on sampled data

diff simply subtracts neighbours. Dividing by the differences of the x-values gives slopes, but they belong to the midpoints between samples, and there is one fewer of them. gradient instead returns one value per sample, using the central difference (y(k+1) − y(k−1)) / (x(k+1) − x(k−1)) inside and one-sided differences at the two ends:

matlab · try it yourself
x = 0:4;
y = x.^2;                           % exact derivative 2x = 0 2 4 6 8
disp(diff(y))                       % slopes between samples (at x = 0.5, 1.5, ...)
disp(diff(y, 2))                    % second differences: constant for a parabola
disp(gradient(y))                   % spacing 1 by default
disp(gradient(y, 0.5))              % if the samples were 0.5 apart
xu = [0 1 3 4 7];                   % uneven spacing: pass the x vector itself
disp(gradient(xu.^2, xu))
   1   3   5   7
   2   2   2
   1   2   4   6   7
    2    4    8   12   14
    1    3    5   10   11

For a parabola the central difference is exact at the interior points (2, 4, 6), while the end points use first-order one-sided differences and are off by one. With uneven spacing the central difference across a wide gap is less accurate (it gives 10 instead of 8 at x = 4).

Remember the shapes: diff output is one element shorter, so plotting it against x needs x(1:end-1) or, better, the midpoints (x(1:end-1) + x(2:end)) / 2.

Finite-difference formulas and their errors

For a function you can evaluate anywhere, the three basic formulas with step h are:

Name Formula Error
Forward (f(x+h) − f(x)) / h proportional to h
Backward (f(x) − f(x−h)) / h proportional to h
Central (f(x+h) − f(x−h)) / (2h) proportional to h²

Taylor's theorem gives the error column. Halving h halves the forward error but quarters the central one. But there is a second error source: subtracting two nearly equal numbers f(x+h) and f(x) loses digits, and the loss grows like eps / h. The total error is therefore smallest for a medium h:

matlab · try it yourself
f = @exp;  x0 = 1;  exact = exp(1);
fprintf('    h      forward    central\n');
for h = 10.^-(1:12)
    fwd = (f(x0 + h) - f(x0)) / h;
    cen = (f(x0 + h) - f(x0 - h)) / (2*h);
    fprintf('%7.0e   %8.1e   %8.1e\n', h, abs(fwd - exact), abs(cen - exact));
end
    h      forward    central
  1e-01    1.4e-01    4.5e-03
  1e-02    1.4e-02    4.5e-05
  1e-03    1.4e-03    4.5e-07
  1e-04    1.4e-04    4.5e-09
  1e-05    1.4e-05    5.9e-11
  1e-06    1.4e-06    1.6e-10
  1e-07    1.4e-07    5.9e-11
  1e-08    6.6e-09    6.6e-09
  1e-09    2.2e-07    6.6e-09
  1e-10    1.5e-06    6.7e-07
  1e-11    3.3e-05    1.0e-05
  1e-12    4.3e-04    2.1e-04

Reading down the table: the forward error falls by 10 per row and the central error by 100 per row, until rounding takes over. The forward formula is best near h ≈ 10⁻⁸ (about √eps), the central one near h ≈ 10⁻⁵ (about eps^(1/3)), and beyond that both get worse again. The digits in the lower rows are pure rounding noise and can differ between MATLAB and Octave; the V shape doesn't. On a log-log plot:

matlab
h = 10.^-(1:12);
fwdErr = abs((exp(1 + h) - exp(1)) ./ h - exp(1));
cenErr = abs((exp(1 + h) - exp(1 - h)) ./ (2*h) - exp(1));
loglog(h, fwdErr, 'o-', h, cenErr, 's-')
set(gca, 'XDir', 'reverse')
legend('forward', 'central'); xlabel('step h'); ylabel('absolute error')
title('Error of d/dx exp(x) at x = 1')

Tip: As a default, use central differences with h = 1e-5 × max(1, |x|). Scaling with |x| keeps the step meaningful for large x.

Better accuracy: Richardson extrapolation

Since the central error behaves like C·h², two estimates with steps h and h/2 can be combined to cancel that term: (4·D(h/2) − D(h)) / 3 has error proportional to h⁴. This trick (the basis of Romberg integration too) gains many digits for the price of two more function evaluations:

matlab · try it yourself
f = @exp;  x0 = 1;  exact = exp(1);
D = @(h) (f(x0 + h) - f(x0 - h)) / (2*h);
h = 0.1;
R = (4 * D(h/2) - D(h)) / 3;
fprintf('D(h)    error %.1e\n', abs(D(h) - exact));
fprintf('D(h/2)  error %.1e\n', abs(D(h/2) - exact));
fprintf('Richardson error %.1e\n', abs(R - exact));
D(h)    error 4.5e-03
D(h/2)  error 1.1e-03
Richardson error 5.7e-07

A trick for analytic functions: the complex step

If f is built from operations that work on complex numbers (exp, sin, .^, *…) and is real for real input, then f(x + ih) ≈ f(x) + ih·f′(x). Taking the imaginary part gives the derivative without any subtraction, so h can be tiny and the result is accurate to machine precision:

matlab · try it yourself
f = @(x) exp(x) .* sin(x) ./ (1 + x.^2);
fprime = @(x) (exp(x).*(sin(x) + cos(x)).*(1 + x.^2) - exp(x).*sin(x).*2.*x) ./ (1 + x.^2).^2;
x0 = 0.7;
cs  = imag(f(x0 + 1i*1e-20)) / 1e-20;
cen = (f(x0 + 1e-5) - f(x0 - 1e-5)) / 2e-5;
fprintf('exact        %.15f\n', fprime(x0));
fprintf('complex step %.15f\n', cs);
fprintf('central      %.15f\n', cen);
fprintf('complex step error below 1e-14: %d, central error about %.0e\n', abs(cs - fprime(x0)) < 1e-14, abs(cen - fprime(x0)));
exact        1.086283981785563
complex step 1.086283981785562
central      1.086283981771574
complex step error below 1e-14: 1, central error about 1e-11

It fails for code that uses abs, max, comparisons or the transpose ' (which conjugates; use .'), so it's a specialist tool, but a remarkably good one for checking hand-written derivatives.

Differentiating noisy measurements

Real data contain measurement errors, and differentiation amplifies them: an error ε in each sample becomes an error of about 2ε/h in a first difference and 4ε/h² in a second difference. Finer sampling makes it worse, not better. Here the "measurements" of a falling object carry an alternating ±5 mm error:

matlab · try it yourself
for dt = [0.1 0.01]
    t = 0:dt:1;
    s = 4.9 * t.^2 + 0.005 * (-1).^(0:numel(t)-1);   % position with error
    v = diff(s) / dt;                                 % velocity at the midpoints
    tm = t(1:end-1) + dt/2;
    a = diff(s, 2) / dt^2;                            % acceleration
    fprintf('dt = %-5g max velocity error %6.3f m/s, max acceleration error %7.1f m/s^2\n', ...
            dt, max(abs(v - 9.8 * tm)), max(abs(a - 9.8)));
end
dt = 0.1   max velocity error  0.100 m/s, max acceleration error     2.0 m/s^2
dt = 0.01  max velocity error  1.000 m/s, max acceleration error   200.0 m/s^2

Without the error both columns would be essentially zero (the differences are exact for a parabola). With it, 10 times finer sampling makes the velocity error 10 times larger and the acceleration error 100 times larger: exactly 2ε/h and 4ε/h². (A central difference such as gradient happens to cancel this particular alternating pattern, but not real, irregular noise.) The cure is to smooth first: fit a low-degree polynomial to a window of points and differentiate the fit (the idea behind Savitzky–Golay filters), or fit a model to all the data with Curve Fitting and differentiate the model.

Gradients on a grid

On a 2-D grid, gradient returns the derivative along the columns (x direction) first and along the rows (y direction) second. That order matches meshgrid, where x varies across columns:

matlab · try it yourself
[X, Y] = meshgrid(0:0.5:2, 0:1:3);
Z = X.^2 + 3*Y;                     % dZ/dx = 2x, dZ/dy = 3
[gx, gy] = gradient(Z, 0.5, 1);     % spacing in x, then in y
disp(gx(1, :))                      % one row: 2x at x = 0, 0.5, ..., 2 (ends one-sided)
fprintf('dZ/dy is 3 everywhere: %d\n', all(gy(:) == 3));
   0.5000   1.0000   2.0000   3.0000   3.5000
dZ/dy is 3 everywhere: 1

quiver(X, Y, gx, gy) draws the gradient as arrows pointing uphill, and del2 gives a discrete Laplacian.

Learn more: derivatives of fitted polynomials in Polynomials, exact derivatives in Symbolic Math, and the inverse operation in Integration & ODEs.

Test yourself

y has 50 elements. How many does diff(y) have?

  1. 50
  2. 49
  3. 48
  4. 25

Why does the forward-difference error grow again when h becomes very small (e.g. 1e-12)?

  1. The Taylor error increases
  2. Rounding: f(x+h) − f(x) subtracts nearly equal numbers and loses digits
  3. MATLAB switches to single precision
  4. exp is inaccurate for small arguments

Halving h in the central difference formula reduces the truncation error by about…

  1. 2 times
  2. 4 times
  3. 8 times
  4. It doesn't change