Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Adaptive derivatives

ProblemDifferentiate a function accurately from its values alone, without choosing a step, and with an estimate of the error; also its Jacobian and Hessian
Devised byLewis Fry Richardson (1911, 1927), extrapolation to zero step; C. J. F. Ridders (1982), the adaptive tableau for derivatives
Accuracy12–15 correct digits for smooth functions; agrees with or improves on scipy.differentiate.derivative, with comparable error estimates
Cost10–20 function evaluations per derivative
Read firstFinite difference derivatives
APIderivative, jacobian, hessian, DerivativeOptions

Overview

A finite difference with a fixed step balances truncation error, which falls as the step shrinks, against rounding error, which grows. At best it reaches about two thirds of the available digits, and only if the step suits the function’s scale. Richardson extrapolation escapes the trade-off. It combines several differences with large, accurately computed steps so as to cancel their truncation errors, and it reports how well the combinations agree, which is an error estimate. This entry implements Ridders’ version, the counterpart of SciPy’s differentiate.derivative, jacobian and hessian.

Where it is used

When you can evaluate a function but not differentiate it by hand, an accurate numerical derivative with an error estimate is the next best thing.

  • Sensitivity analysis. Engineers differentiate the output of a simulation (a finite-element solver, a circuit simulator) with respect to a design parameter without rewriting the solver.
  • Optimisation and root finding. Gradient-based methods need derivatives of “black-box” models; an adaptive estimate avoids hand-tuning the step size.
  • Experimental data and calibration. Estimating a slope from a function that is expensive or noisy to evaluate, with a stated uncertainty.

History

Lewis Fry Richardson (1911) noticed that an approximation whose error is a known power series in the step can be extrapolated to zero step, and called it “the deferred approach to the limit” (1927). Werner Romberg’s integration (1955) applied it to quadrature. C. J. F. Ridders (1982) organised it for derivatives as a Neville tableau with a built-in error estimate and stopping rule, the version popularised by Numerical Recipes. SciPy 1.15 (2024) added scipy.differentiate, which takes the same approach with higher-order stencils.

The idea

The central difference has an error expansion in even powers, . With at steps and , the combination cancels the term. Repeating on the results cancels , and so on. Ridders’ tableau computes this for a decreasing sequence of steps:

Each entry has two parents. Its difference from them estimates its error, and the entry with the smallest such difference is the answer. The tableau starts from a large step (0.5 by default), where rounding error is negligible, and extrapolates towards zero without ever evaluating at a tiny step. When the diagonal stops improving, rounding has caught up and the iteration stops.

Figure 1.2. Error against the step.

The best fixed step gives an error of about . Ridders’ tableau reaches with ten evaluations, using only five steps, from 0.5 down to 0.03.

The Jacobian applies the method to each coordinate direction of each component. The Hessian is the Jacobian of the gradient, each gradient component itself computed by the method, and is then symmetrised.

Algorithm

derivative(f, x, options): initial_step; row 0 is . For each further row: ; new row extended by the extrapolation formula; keep the entry with the smallest difference from its parents and that difference as the error. Stop when the error is within tolerance, or when the diagonal grows by more than twice the error after the error has become small, or after max_iterations rows.

Implementation

/// `f'(x)` with an error estimate, by Ridders' extrapolation of central differences.
///
/// Row `i` of the tableau starts from `D(hᵢ) = (f(x + hᵢ) − f(x − hᵢ)) / 2hᵢ` with `hᵢ = h/cⁱ`; each
/// column `j` removes the next even power of `h`: `T(i, j) = (c^{2j} T(i, j−1) − T(i−1, j−1)) /
/// (c^{2j} − 1)`. The best estimate is the entry whose difference from its two parents is
/// smallest. Extrapolation stops when the diagonal grows by more than twice the best error, the
/// sign that rounding error dominates.
pub fn derivative(f: impl Fn(f64) -> f64, x: f64, options: DerivativeOptions) -> Result<DerivativeResult, ErrorsJSL> {
    if !x.is_finite() || !(options.initial_step > 0.0) || !(options.step_factor > 1.0) || options.max_iterations == 0 {
        return Err(ErrorsJSL::InvalidInputRange("need a finite point, a positive step and a step factor above 1"));
    }
    let c2 = options.step_factor * options.step_factor;
    let mut h = options.initial_step;
    let mut nfev = 0;
    let mut central = |h: f64| {
        nfev += 2;
        (f(x + h) - f(x - h)) / (2.0 * h)
    };
    let mut prev_row = vec![central(h)];
    let (mut best, mut err) = (prev_row[0], f64::INFINITY);
    for iteration in 1..options.max_iterations {
        h /= options.step_factor;
        let mut row = vec![central(h)];
        let mut fac = c2;
        for j in 1..=prev_row.len() {
            let t = (row[j - 1] * fac - prev_row[j - 1]) / (fac - 1.0);
            fac *= c2;
            let errt = (t - row[j - 1]).abs().max((t - prev_row[j - 1]).abs());
            if errt <= err {
                err = errt;
                best = t;
            }
            row.push(t);
        }
        // The divergence test is meaningful only once the steps are small enough for the
        // extrapolation to have converged at least roughly: after a few rows.
        // Stop on divergence only once the estimate is already fairly accurate: early rows from a
        // step that is too large for the function are inaccurate rather than noisy.
        let diverging = iteration >= 3 && err <= f64::EPSILON.sqrt() * best.abs().max(1e-300) && (row[row.len() - 1] - prev_row[prev_row.len() - 1]).abs() >= 2.0 * err;
        prev_row = row;
        if err <= options.atol + options.rtol * best.abs() || diverging {
            break;
        }
    }
    Ok(DerivativeResult { df: best, error: err, nfev, converged: err <= options.atol + options.rtol * best.abs() || err.is_finite() && err <= 1e-8 * best.abs().max(1.0) })
}
  • initial_step is absolute, as in SciPy. For functions that vary on a scale far from 1, scale it accordingly.
  • The divergence test applies only after the estimate is within in relative terms. Before that, large changes in the diagonal mean the step is still too large, not that rounding dominates.

In practice

Each function is differentiated at , 1 and 2.7, and the largest errors are compared with SciPy 1.17.1’s differentiate.derivative (references from book/generator/data/make_sampled_refs.py):

Table 1.4. Adaptive derivatives against SciPy.

f(x), at x = 0.3, 1, 2.7true relative error (library / SciPy)estimated error (library / SciPy)evaluations (library / SciPy)
eˣ1e-15 / 1e-143e-12 / 3e-1210 / 11
sin 3x9e-16 / 3e-131e-12 / 7e-1112 / 13
ln(1 + x)7e-15 / 2e-127e-12 / 4e-1012 / 13
arctan 10x1e-11 / 5e-118e-9 / 8e-914 / 15

Both methods reach 11–15 digits, with comparable error estimates and evaluation counts. SciPy’s higher-order stencils converge differently, so the two are not expected to agree to rounding. Both are compared with the exact derivative instead.

Strengths

  • No step to choose, and near machine precision for smooth functions.
  • An error estimate with every result.

Weaknesses

  • Needs the function on both sides of at distances up to initial_step. Use one-sided differences near a domain boundary.
  • Noisy functions defeat extrapolation. Their derivative should come from a fitted model instead.
  • The Hessian costs derivatives, each about 10–20 evaluations.

Exercises

  1. Show that the central difference has an error expansion in even powers of for a smooth .
  2. With , show that is the five-point stencil of finite differences.
  3. Why does starting from a large step not spoil the accuracy, while evaluating at a tiny step would?
Hints and answers
  1. The Taylor series of give , with odd powers only, so dividing by leaves even powers.
  2. Expand: , which is the stencil with spacing .
  3. The truncation error is removed exactly by the extrapolation, up to higher orders. The rounding error of a difference is about , which is small for large and is amplified only by the modest extrapolation weights.

Further reading

  • C. J. F. Ridders, “Accurate computation of F′(x) and F′(x)F″(x)”, Advances in Engineering Software 4 (1982) 75–76.
  • W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery, Numerical Recipes, 3rd ed., Cambridge University Press, 2007, section 5.7.
  • L. F. Richardson and J. A. Gaunt, “The deferred approach to the limit”, Philosophical Transactions of the Royal Society A 226 (1927) 299–361.