Finite difference derivatives
| Problem | Approximate , higher derivatives, gradients, Hessians and Jacobians from values of |
| Devised by | Difference quotients: Newton and Leibniz (1670s), Brook Taylor (1715); difference formulas of higher order from interpolation: Newton, Stirling and Bessel (18th century); step-size analysis in floating point: the early numerical analysts, systematised in texts such as Gill, Murray and Wright (1981) |
| Accuracy | Central difference: about (10 digits); five-point first derivative: about (13 digits); each higher derivative loses more |
| Cost | Two evaluations (central), four or five (five-point); a gradient costs , a Hessian about |
| Read first | Preliminaries: floating-point arithmetic |
| API | derivative_2_point, derivative_stencil, gradient_2_point, hessian_2_point, jacobian_2_point |
Overview
The derivative is defined as the limit of a difference quotient,
A computer cannot take a limit, but it can evaluate the quotient for one small value of . That is a finite difference: stop short of the limit and use a small but finite step .
The idea could not be simpler. The difficulty is in choosing , because two errors pull in opposite directions:
- If is too large, the quotient is the slope of a chord that is still some way from the tangent. This is the truncation error, and it shrinks as shrinks.
- If is too small, the two function values and agree in nearly all their digits. Subtracting them cancels those digits and leaves mostly rounding error, which is then divided by the small number . This is the rounding error, and it grows as shrinks.
A quick experiment shows both. Take at , where the exact derivative is 1. With the quotient is 1.0517, wrong in the second digit because the step is too coarse. With the computed quotient is 1.1102, which is worse: and 1 differ only in their last binary digit or two, so their difference is almost entirely rounding error. The best answer lies somewhere in between. Understanding this trade-off, and choosing to balance it, is the heart of numerical differentiation, and the rest of this entry works it out step by step.
Where it is used
Finite differences are the simplest way to get a derivative from function values, and they underlie much of scientific computing.
- Optimisation and Newton’s method. Gradients, Jacobians and Hessians are often approximated by differences when the analytic form is unavailable, as in most solvers of this book.
- Gradient checking. Machine-learning engineers compare a hand-coded backpropagation gradient with a finite-difference estimate to catch bugs.
- Differential equations. The same difference formulas, applied to a grid, turn a PDE such as the heat equation into a system of algebraic equations (see finite difference methods).
History
Difference quotients are the starting point of the calculus: both Newton and Leibniz reasoned with the ratios of small increments before passing to the limit. Brook Taylor’s Methodus incrementorum (1715) developed the calculus of finite differences systematically, and the interpolation formulas of Newton, James Stirling and Friedrich Bessel gave difference formulas of any order, used for centuries to differentiate tables of values by hand.
The modern question, how to choose the step in floating-point arithmetic, came with the computer. Its answer, that the best step balances the truncation and rounding errors and scales with a power of the machine precision, became standard in the optimisation literature of the 1970s, where finite difference gradients and Jacobians are essential; Philip Gill, Walter Murray and Margaret Wright’s Practical Optimisation (1981) gives a careful treatment.
The idea
The argument has four parts. First we measure the truncation error of a difference quotient with Taylor’s theorem. Then we measure the rounding error, and balance the two to find the best step. After that we see how using more points gives more accurate formulas, and finally how the same ideas carry over to functions of several variables.
Truncation error
Taylor’s theorem expresses the values of near through its derivatives at . For a step of and a step of it gives
The two expansions differ only in the signs of the odd powers of .
The forward difference. Take the first expansion, subtract from both sides and divide by :
The left side is the quantity we compute and the first term on the right is the quantity we want. Everything else is the truncation error, and for small its largest part is . The error is proportional to , so we say the forward difference is first-order accurate: halving the step halves the error.
The central difference. Now subtract the second expansion from the first. The terms and appear in both with the same sign, so they cancel, while the odd terms double:
Dividing by gives the central difference
Its error is proportional to : it is second-order accurate, so halving the step divides the error by four. It costs two evaluations of , the same as the forward difference, and the improvement comes entirely from the symmetry of the two points about .
The example from the overview shows the difference. At with , every derivative of equals 1, so the predicted errors are and . The computed quotients are
just as predicted. This symmetric cancellation is the same phenomenon that makes the midpoint rule better than it looks.
Rounding error and the optimal step
If truncation were the only error we would make as small as possible. Rounding prevents that.
A double-precision number holds about 16 significant digits, so a computed function value carries a relative error of about at best. In absolute terms each of and is wrong by about . Their difference is therefore also wrong by about , however small the difference itself is. The central difference then divides by , so the rounding error in the result is about (we ignore factors of 2, which do not change the conclusion). Adding the two errors,
The first term falls as decreases and the second rises, so has a minimum. To find it, set the derivative with respect to to zero:
For a function whose values and derivatives are of ordinary size ( and near 1) this says . Substituting back, both terms of are then of size : about ten correct digits. That is the best a central difference can do in double precision, and it is why a derivative computed this way never has the full 16 digits of the function values.
The general rule. The same calculation works for any difference formula. Suppose the formula approximates the -th derivative with a truncation error proportional to . Its denominator contains , so the rounding error is proportional to , and
for some constants and . Setting gives , that is . Dropping the constants,
For the forward difference (, ) this gives a step of and only eight digits; for the central difference (, ) it reproduces the result above.
The figure shows the trade-off for derivatives of . Both axes are logarithmic, so an error proportional to appears as a straight line of slope . Each curve is a V. On the right arm the truncation error dominates, and the slopes are 2 and 4, the orders of the formulas. On the left arm the rounding error dominates, and the slopes are , and , one for each order of derivative .
Figure 1.1. Error against step size.
The library’s default steps sit at the bottom of each V:
Table 1.3. Error terms and default steps of the finite-difference formulas.
| formula | truncation error | rounding error | default relative step | error for at |
|---|---|---|---|---|
| central difference, | 2.3e-11 | |||
| five-point, | 8.9e-14 | |||
| five-point, | 1.8e-10 | |||
| five-point, | 4.3e-7 | |||
| five-point, | 2.5e-5 |
Two practical details complete the picture.
- The steps are relative: the step actually used at is . This suits functions that vary on the scale of . An absolute step of would be meaningless at , where neighbouring floating-point numbers are about apart. The exception is a function that oscillates on a scale of one at large , such as at ; it needs a smaller step, passed explicitly.
- The sum is rounded to the nearest floating-point number, so the step actually taken is not quite . The discrepancy is about , which relative to the step is : for and that is , as large as the whole error budget of the central difference. The library therefore replaces by , the step actually taken. When is much smaller than , which is the case that matters, the two numbers being subtracted are within a factor of two of each other, and floating-point arithmetic then performs the subtraction exactly (Sterbenz’s lemma). The divisor thus matches the points at which is evaluated.
Higher-order stencils
A stencil is the set of points a difference formula uses, together with their weights. The central difference cancelled one term of the Taylor series by combining two points. Combining more points cancels more terms. With the five points , and :
Both are fourth-order accurate (). The same five points also give second-order formulas for and .
Where do the weights come from? One systematic route is Richardson extrapolation: combine two estimates made with different steps so that their leading errors cancel. Write for the central difference with step . From the previous section, its error contains only even powers of :
where and does not depend on . Doubling the step replaces by :
Multiplying the first line by 4 and subtracting the second removes the term:
The combination on the left is fourth-order accurate. Writing out and in terms of function values turns it into the five-point formula for above (exercise 2). Romberg integration applies exactly the same trick to the trapezoid rule.
What does higher order buy? Put , into the general rule: the optimal step grows to and the error falls to , about thirteen digits. A higher-order formula tolerates a larger step, and a larger step means less cancellation.
Higher derivatives are inherently harder, because the rounding error is divided by . For the fourth derivative from five points (, ) the rule gives an error of : only about five digits.
Gradients, Hessians and Jacobians
For a function of several variables, a partial derivative is an ordinary derivative along one coordinate with the others held fixed, so it can be computed by a central difference along that coordinate. Write for the unit vector along coordinate .
- The gradient of is the vector of its partial derivatives. Component is , so the whole gradient costs evaluations.
- The Jacobian of a vector function is the matrix of partial derivatives . One pair of evaluations of , at , gives a whole column, so the cost is again evaluations of the vector function.
- The Hessian is the matrix of second partial derivatives. Its diagonal entries use the three-point second difference . Its off-diagonal entries apply a central difference in direction to a central difference in direction , which uses the four corners of a small rectangle around :
Both Hessian formulas are second-order approximations of a second derivative (, ), so the general rule gives the step . The number of entries, and so the cost, grows like , which is why optimisation methods such as BFGS build up Hessian approximations from gradients instead.
Better than finite differences
Two techniques avoid the cancellation entirely, when they apply.
The complex step. Suppose is analytic and the program that computes it accepts complex arguments. Take a step of in the imaginary direction. Taylor’s theorem holds for complex steps too:
If is real for real arguments, the derivative sits alone in the imaginary part, with a correction of order . Hence
with an error of order . No subtraction of nearly equal numbers takes place, so there is no rounding penalty for a small step: can be as small as , and the result is accurate to machine precision. More generally, Cauchy’s integral formula gives derivatives of any order.
Automatic differentiation applies the chain rule to each elementary operation of the program that computes , producing derivatives that are exact up to rounding.
Both techniques require access to more than function values: the first needs complex arithmetic inside and the second needs its source code. That is why finite differences remain the universal fallback.
Algorithm
A derivative of a function of one variable, of order , by a formula of order .
- Choose the step. Unless the caller supplies one, take the relative step from the table above, and scale it to the size of the argument: .
- Use the step actually taken. Replace by , so that the divisor equals the distance between the points at which is actually evaluated.
- Evaluate at the points of the stencil: for the central difference, and , , for the five-point formulas.
- Combine the values with the weights of the formula and divide by .
The cost is two evaluations of for the central difference and four or five for a five-point formula (the first and third derivatives do not use the centre value).
Gradient and Jacobian at . For each coordinate :
- choose from as in steps 1 and 2 above;
- evaluate the function at and ;
- the difference of the two values, divided by , is component of the gradient, or column of the Jacobian;
- restore before moving to the next coordinate.
The cost is evaluations.
Hessian. With the steps :
- evaluate once;
- for each , evaluate and form the diagonal entry by the three-point second difference;
- for each pair , evaluate at the four corners , form the cross difference, and store it in both positions and .
The cost is evaluations.
Implementation
The central difference and the five-point formulas:
Ok((f(x + h) - f(x - h)) / (2.0 * h))
let value = match order {
DerivativeStencilOrder::FirstOrder => (-p2 + 8.0 * p1 - 8.0 * m1 + m2) / (12.0 * h),
DerivativeStencilOrder::SecondOrder => (-p2 + 16.0 * p1 - 30.0 * z + 16.0 * m1 - m2) / (12.0 * h * h),
DerivativeStencilOrder::ThirdOrder => (p2 - 2.0 * p1 + 2.0 * m1 - m2) / (2.0 * h.powi(3)),
DerivativeStencilOrder::FourthOrder => (p2 - 4.0 * p1 + 6.0 * z - 4.0 * m1 + m2) / h.powi(4),
};
- One fixed absolute step cannot suit every formula. A step of is near-optimal for the central difference at , but for the five-point fourth derivative the rounding error is then about and the formula returns noise. The default steps therefore depend on the formula, as in the table above.
- The step for each coordinate is chosen separately, scaled by that coordinate’s magnitude.
In practice
//! Finite difference derivatives, gradients, Hessians and Jacobians.
//!
//! Run with `cargo run -p lib_jsl_derivatives --example finite_difference_derivatives`.
use lib_jsl_derivatives::derivatives_1d_scalar::{DerivativeStencilOrder, derivative_2_point, derivative_stencil};
use lib_jsl_derivatives::derivatives_vectors::{gradient_2_point, hessian_2_point, jacobian_2_point};
fn main() {
// d/dx of sin x at x = 1, with the default (balanced) step and with steps too large and too small.
let exact = 1f64.cos();
for step in [None, Some(1e-2), Some(1e-12)] {
let d = derivative_2_point(&f64::sin, 1.0, step).unwrap();
println!("central difference, step {step:?}: error {:.1e}", (d - exact).abs());
}
let d = derivative_stencil(&f64::sin, 1.0, None, DerivativeStencilOrder::FirstOrder).unwrap()[0];
println!("five-point stencil, default step: error {:.1e}", (d - exact).abs());
// The Rosenbrock function f = (1 − x)² + 100 (y − x²)² at (−1.2, 1).
let rosenbrock = |v: &[f64]| (1.0 - v[0]).powi(2) + 100.0 * (v[1] - v[0] * v[0]).powi(2);
let x = [-1.2, 1.0];
let g = gradient_2_point(&rosenbrock, &x, None).unwrap();
println!("gradient {g:.6?} (exact [-215.6, -88])");
let h = hessian_2_point(&rosenbrock, &x, None).unwrap();
println!("Hessian {h:.4?} (exact [[1330, 480], [480, 200]])");
// The Jacobian of polar-to-Cartesian coordinates (r, θ) ↦ (r cos θ, r sin θ); its determinant is r.
let polar = |v: &[f64]| vec![v[0] * v[1].cos(), v[0] * v[1].sin()];
let j = jacobian_2_point(&polar, &[2.0, 0.5], None).unwrap();
println!("Jacobian determinant {:.10} (exact 2)", j[0][0] * j[1][1] - j[0][1] * j[1][0]);
}
Strengths
- Needs nothing but function values: works for any function, including black-box procedures.
- Simple, cheap for low dimensions, and accurate to about ten digits with a balanced step.
Weaknesses
- Accuracy is fundamentally limited by cancellation, more severely for higher derivatives.
- Noisy functions (simulations, measured data) can make finite differences useless, since the noise plays the role of and is far larger.
- The cost of gradients grows with the dimension, and that of Hessians with its square.
Exercises
- Show that the forward difference has optimal step and error (eight digits). Why is the central difference worth its extra evaluation?
- Derive the five-point first-derivative formula by Richardson extrapolation of the central difference.
- Suppose is computed with a relative error of (for example, by an iterative solver). What step and accuracy should you expect for the central difference?
- Implement the complex-step derivative for at and compare it with the central difference at a range of steps.
- Use
hessian_2_pointon near . Why does the default relative step work poorly here, and what would you do?
Hints and answers
- The error is about (truncation plus rounding). Setting the derivative with respect to to zero gives and an error of the same size, about . For the central difference the truncation term is , so the best step is and the error : three more digits for one more evaluation.
- The central difference is . Eliminate the term with , which equals .
- Replace by in the balance of exercise 1: and an error near , up to the constants set by . Noisy functions need large steps and give few digits.
- There is no subtraction in , so is fine and the result is correct to nearly full precision. The central difference is best near with an error around and degrades on both sides. The function must be analytic and written without
abs, comparisons or conjugation. - Look at how much each coordinate step changes the product , which is what responds to: relative steps in and are scaled by very different magnitudes. Second differences want a change of order in the argument. Rescaling the variables so both are of order one, or choosing the steps by hand, removes the problem.
Further reading
- B. Taylor, Methodus incrementorum directa et inversa, London, 1715.
- P. E. Gill, W. Murray and M. H. Wright, Practical Optimization, Academic Press, 1981, section 8.6. Step-size selection for finite difference gradients.
- J. N. Lyness and C. B. Moler, “Numerical differentiation of analytic functions”, SIAM Journal on Numerical Analysis 4 (1967) 202–210, and W. Squire and G. Trapp, “Using complex variables to estimate derivatives of real functions”, SIAM Review 40 (1998) 110–112. The complex step.
- A. Griewank and A. Walther, Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation, 2nd ed., SIAM, 2008.
- N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002. Rounding errors in general.