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

Piecewise and spline interpolation

ProblemInterpolate data , , by a function that is simple on each interval: lines or cubics
Devised bySplines: Isaac Schoenberg (1946), after the draughtsman’s flexible spline; algorithms: Carl de Boor (1960s–70s). Cubic Hermite methods: Akima (1970), Fritsch and Carlson’s monotone PCHIP (1980), Catmull and Rom (1974)
AccuracyLinear: . Natural cubic spline: in the interior, near ends where . PCHIP and Akima: for smooth data
CostLinear and Hermite methods: set-up; spline: one tridiagonal solve. Each evaluation: a binary search, then
Read firstPolynomial interpolation
APILinearInterpolator, NaturalCubicSplineInterpolator, pchip, akima, cubic_basis, PiecewiseHermite

Overview

Polynomial interpolation fits one polynomial through all the data, which is excellent at well-chosen points and dangerous at equally spaced or irregular ones. Piecewise interpolation instead fits a low-degree polynomial on each interval between neighbouring data points. The result can be evaluated anywhere quickly, is not troubled by the number of points, and a bad data point affects only its neighbourhood.

The methods in this entry differ in how they join the pieces. Linear interpolation joins straight lines and has corners. Cubic splines choose cubics whose first and second derivatives are continuous: the smoothest possible curve, but a global one, which can overshoot near steep changes. Cubic Hermite methods (PCHIP, Akima, Catmull-Rom) choose a slope at each data point from nearby data and fit each cubic to the end values and slopes: they are local, and PCHIP in particular never overshoots monotone data.

Where it is used

Cubic splines give the smooth, well-behaved curve through data that a draftsman’s flexible spline once did.

  • Computer graphics and animation. Smooth paths through key positions.
  • Engineering data. Smooth interpolation of material curves, calibration tables and trajectories, with continuous first and second derivatives.
  • Numerical methods. Splines are used to integrate and differentiate tabulated functions, and as the model in smoothing and regression.
  • Naming. The word “spline” is the flexible strip used by shipbuilders to draw hull curves through fixed points.

History

Before computers, draughtsmen drew smooth curves through points with a spline: a thin flexible strip of wood or metal held in place by lead weights called ducks. A bent elastic strip minimises its bending energy, approximately , and between the weights its shape is a cubic.

Isaac Schoenberg named and founded the mathematical theory of splines in 1946, working on smoothing actuarial tables at the US Army’s Ballistic Research Laboratory. The aircraft and automotive industries adopted them in the 1960s for designing surfaces, and Carl de Boor’s work, culminating in A Practical Guide to Splines (1978), provided the stable algorithms still in use.

Hiroshi Akima (1970) proposed a local cubic interpolant that avoids the wiggles of global splines on data that changes abruptly. Edwin Catmull and Raphael Rom (1974) introduced their spline for computer graphics, where it still drives animation paths. Frederick Fritsch and Ralph Carlson (1980) derived conditions under which a piecewise cubic Hermite interpolant preserves monotonicity, leading to PCHIP, the shape-preserving interpolant of MATLAB and SciPy.

The idea

Throughout, the data are with the abscissas in increasing order. The points are called nodes (or knots), is the width of interval , and is the slope of the straight line across it, called the secant.

Locating the interval

Every piecewise method first finds the interval containing the evaluation point. Because the nodes are sorted, this is done by bisection: compare with the middle node, discard the half that cannot contain the point, and repeat, which takes steps. Interpolators are often evaluated at many nearby points in sequence, as when drawing a curve. They remember the last interval and check it first (“hunting”), which makes most evaluations . Bisection requires the abscissas to be in increasing order, and the library’s constructors check this.

Linear interpolation

The simplest choice joins neighbouring points by straight lines. On ,

How accurate is this if the data are samples of a function ? Each piece is the polynomial interpolant through two points, so the interpolation error formula applies with : the error is . The product is largest in magnitude at the midpoint, where it equals . The error is therefore at most , with the largest interval. Linear interpolation is second-order accurate, robust, and never leaves the range of the data, but the curve has a corner at every data point.

Cubic splines

To remove the corners we need curved pieces. Cubics are the lowest degree with enough freedom to match the neighbours smoothly on both sides. A cubic spline is a function that is a cubic on each interval and whose first and second derivatives are continuous at the interior nodes.

Counting the conditions. With points there are cubics, each with 4 coefficients: unknowns. The conditions are:

  • each cubic passes through the data at both ends of its interval: equations;
  • is continuous at each of the interior nodes: equations;
  • is continuous at each interior node: more.

That makes equations, two short. Two end conditions complete the system. The natural spline sets at both ends. The name comes from the draughtsman’s spline, a thin flexible strip held against pins: beyond the last pin the strip is free, and a free strip is straight.

Reducing to a tridiagonal system. Solving equations directly would be wasteful. A better choice of unknowns makes most of them trivial. Write the cubic on interval as

so that . The plan is to express everything in terms of the .

  1. Continuity of : the second derivative must reach at , which gives .
  2. Interpolation: , with from step 1, gives .
  3. Continuity of : the slope at the right end of interval must equal , the slope at the left end of interval . Substituting steps 1 and 2 leaves an equation in the ’s alone:

There is one such equation for each interior node, and the natural end conditions supply . Each equation involves only three neighbouring unknowns, so the matrix of the system is tridiagonal. It is also diagonally dominant (the diagonal entry exceeds the sum of the other two), which guarantees that elimination without pivoting is stable. The system is solved in operations, after which steps 1 and 2 give the remaining coefficients.

Why splines are smooth. The natural spline has a remarkable optimality property.

Minimum curvature. Among all functions with a square-integrable second derivative that interpolate the data, the natural cubic spline minimises .

The integral is approximately the bending energy of a thin elastic strip, so this is the mathematical form of the draughtsman’s tool: the strip settles into the shape of least energy. The property explains the spline’s smoothness and also its weakness. Because the curvature is spread over the whole curve, a sudden rise in the data pulls the curve into oscillations on both sides. Every data point affects the spline everywhere, though the influence dies away with distance.

The price of the natural end condition. If the underlying function has at the ends, the natural condition imposes something false there. The error near the ends is then only , although it remains in the interior. For on , whose second derivative is nowhere zero, the library’s results show this clearly:

Table 3.2. Convergence of linear and natural spline interpolation.

pointslinearnatural splinenatural spline, middle half onlyPCHIPAkimaCatmull-Rom
61.2e-25.3e-31.5e-38.2e-48.2e-47.8e-3
113.2e-31.3e-38.9e-51.1e-41.1e-42.0e-3
218.3e-43.3e-44.9e-71.4e-51.4e-55.0e-4
412.1e-48.3e-52.1e-91.8e-61.8e-61.3e-4
815.3e-52.1e-51.3e-102.3e-72.3e-73.1e-5

Each row halves . The natural spline’s maximum error falls by a factor of four per halving (second order, from the ends). The middle-half column does not follow a single pattern: its ratios are about 17, then far larger, then 16 again. The reason is that the end error does not stay at the ends. It is a disturbance that dies out as one moves inward, by roughly a factor at every knot. The middle half lies a quarter of the interval from either end, which is a number of knots that doubles each time is halved, so the leftover disturbance shrinks much faster than any power of (hence the very large ratios) until it falls below the interior’s own error, after which the ratio settles at sixteen. This is why the natural end condition is acceptable in practice: its damage stays near the boundary. A clamped spline, which uses the true end slopes, or the not-a-knot condition, which makes the first two and the last two pieces the same cubic, would restore fourth order everywhere.

Cubic Hermite interpolation

A different way to make a smooth piecewise cubic is to decide the slope of the curve at every node first. A cubic has four coefficients, and on each interval there are four conditions: the values , and the slopes , at its two ends. So each interval has a unique cubic, which can be written down directly:

where is the width of the interval and runs from 0 to 1 across it. The four cubics

are the Hermite basis. Each one takes care of exactly one condition: has value 1 at , value 0 at and zero slope at both ends; has slope 1 at and is otherwise zero in value and slope at the ends; and do the same at . (The factors of convert slopes with respect to into slopes with respect to .)

Neighbouring pieces share the value and slope at their common node, so the result has a continuous first derivative. The second derivative is in general discontinuous, so the curve is slightly less smooth than a spline. In exchange the method is local: no linear system is solved, and the curve on an interval depends only on nearby data. The methods differ only in how they choose the slopes.

  • Catmull-Rom (cubic_basis with tension 0): the slope of the line through the two neighbours, , a central difference. Tension scales it by , flattening the curve at the nodes.
  • Akima: a weighted average of the two neighbouring secants and . The weight of each is the change in the secants on the far side of the node. Where the data change abruptly on one side, the slope follows the other, smoother side, which suppresses wiggles.
  • PCHIP (piecewise cubic Hermite interpolating polynomial): zero where the data have a local extremum (the neighbouring secants differ in sign), and otherwise a weighted harmonic mean of the two secants. A harmonic mean is dominated by the smaller of its arguments, so the slope is never much steeper than the flatter neighbouring secant. Fritsch and Carlson showed that this keeps the interpolant monotone wherever the data are monotone.

Figure 3.4. Akima's test data.

Akima’s classic data are flat and then rise steeply. The natural spline dips below the flat values and overshoots the rise, the global oscillation described above. Akima’s interpolant follows the data with only a small ripple, and PCHIP is monotone throughout. In the example below, only PCHIP stays within the range of the data: Akima and Catmull-Rom can still overshoot slightly.

Algorithm

Every method has a set-up, done once, and an evaluation, done for each point.

Locating the interval (shared by all the methods). Given :

  1. if lies in the interval found by the previous call, use it;
  2. otherwise bisect: keep two indices bracketing , compare with the node midway between them, and move one index, until they are adjacent. Points outside the data use the first or the last interval.

Linear. No set-up. Evaluate the straight line through the two ends of the interval.

Natural cubic spline.

  1. Set-up. Form the tridiagonal system for , with . Solve it by the Thomas algorithm, which is Gaussian elimination specialised to three diagonals: one forward sweep eliminates the subdiagonal, and one backward sweep substitutes. Then compute and for each interval from the by the formulas above. Cost: .
  2. Evaluation. Locate the interval and evaluate with .

Hermite methods (Catmull-Rom, Akima, PCHIP).

  1. Set-up. Compute the secants . Compute a slope at every node by the method’s rule. The rules need neighbours on both sides, so the two ends are treated specially: PCHIP uses a three-point formula there, limited so that it cannot break monotonicity, and Akima extrapolates two extra secants beyond each end. Cost: .
  2. Evaluation. Locate the interval, compute , and evaluate the Hermite form with the values and slopes at its two ends.

Implementation

The natural spline set-up:

        let n = self.x_values.len();
        let a = self.y_values.to_owned();
        let mut b = R1D::zeros(n - 1);
        let mut c = R1D::zeros(n);
        let mut d = R1D::zeros(n - 1);

        // Step 1: compute h
        let h = R1D::from_iter(self.x_values.iter()
                .zip(self.x_values.iter().skip(1))
                .map(|(&x0, &x1)| x1 - x0)
        );

        // Step 2: set up tridiagonal system
        let mut alpha = R1D::zeros(n);
        for i in 1..n - 1 {
            alpha[i] = (3.0 / h[i]) * (a[i + 1] - a[i])
                - (3.0 / h[i - 1]) * (a[i] - a[i - 1]);
        }

        // Step 3: solve tridiagonal system for c (Thomas algorithm)
        let mut l = R1D::zeros(n);
        let mut mu = R1D::zeros(n);
        let mut z = R1D::zeros(n);

        l[0] = 1.0;
        mu[0] = 0.0;
        z[0] = 0.0;

        for i in 1..n - 1 {
            l[i] = 2.0 * (self.x_values[i + 1] - self.x_values[i - 1]) - h[i - 1] * mu[i - 1];
            mu[i] = h[i] / l[i];
            z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / l[i];
        }

        l[n - 1] = 1.0;
        z[n - 1] = 0.0;
        c[n - 1] = 0.0;

        for j in (0..n - 1).rev() {
            c[j] = z[j] - mu[j] * c[j + 1];
            b[j] = ((a[j + 1] - a[j]) / h[j]) - (h[j] * (c[j + 1] + 2.0 * c[j]) / 3.0);
            d[j] = (c[j + 1] - c[j]) / (3.0 * h[j]);
        }
  • All Hermite methods share PiecewiseHermite, which also accepts any slopes you supply, for example derivatives known from the physics.
  • Outside the data range every method extends its end piece; extrapolation far beyond the data is rarely meaningful.
  • The linear interpolator tolerates repeated abscissas (it takes the left value), which is occasionally convenient for step-like tables; the other methods require strictly increasing .

In practice

A temperature profile across a thermocline:

//! Piecewise interpolation: linear, natural cubic spline, PCHIP, Akima and Catmull-Rom.
//!
//! Run with `cargo run -p lib_jsl_interpolation --example interpolation_splines`.

use lib_jsl_core::R1D;
use lib_jsl_interpolation::interpolation_trait::InterpolationTrait;
use lib_jsl_interpolation::one_d::akima::akima;
use lib_jsl_interpolation::one_d::cubic_basis::cubic_basis;
use lib_jsl_interpolation::one_d::linear_interpolator::LinearInterpolator;
use lib_jsl_interpolation::one_d::natural_cubic_spline_interpolator::NaturalCubicSplineInterpolator;
use lib_jsl_interpolation::one_d::pchip::pchip;

fn main() {
    // A temperature profile measured at uneven depths, rising steeply across a thermocline.
    let depth = R1D::from_vec(vec![0.0, 5.0, 10.0, 15.0, 18.0, 20.0, 22.0, 25.0, 35.0, 50.0]);
    let temperature = R1D::from_vec(vec![20.0, 20.0, 19.9, 19.8, 17.0, 12.0, 8.5, 7.0, 6.0, 5.5]);
    let mut linear = LinearInterpolator::new(depth.view(), temperature.view()).unwrap();
    let mut spline = NaturalCubicSplineInterpolator::new(depth.view(), temperature.view()).unwrap();
    let mut monotone = pchip(depth.view(), temperature.view()).unwrap();
    let mut local = akima(depth.view(), temperature.view()).unwrap();
    let mut cardinal = cubic_basis(depth.view(), temperature.view(), 0.0).unwrap();
    println!("depth   linear   spline    PCHIP    Akima  Catmull-Rom");
    for z in [2.5, 12.5, 16.5, 19.0, 21.0, 30.0, 42.0] {
        println!(
            "{z:5.1} {:8.3} {:8.3} {:8.3} {:8.3} {:8.3}",
            linear.interpolate_at(z).unwrap(),
            spline.interpolate_at(z).unwrap(),
            monotone.interpolate_at(z).unwrap(),
            local.interpolate_at(z).unwrap(),
            cardinal.interpolate_at(z).unwrap()
        );
    }
    // The spline overshoots the 20 °C surface value; PCHIP cannot leave the range of its data.
    let max = |f: &mut dyn FnMut(f64) -> f64| (0..=500).map(|i| f(i as f64 * 0.1)).fold(f64::MIN, f64::max);
    println!("maximum on [0, 50]: spline {:.3}, PCHIP {:.3}", max(&mut |z| spline.interpolate_at(z).unwrap()), max(&mut |z| monotone.interpolate_at(z).unwrap()));
}

Strengths

  • Any number of points, irregular spacing, fast evaluation.
  • Splines give the smoothest curve, and fourth-order accuracy away from the ends.
  • PCHIP preserves monotonicity and never overshoots; Akima resists wiggles near abrupt changes.

Weaknesses

  • Splines overshoot near steep changes and need good end conditions for full accuracy.
  • Hermite methods have discontinuous second derivatives, which matters for some applications (curvature, acceleration).
  • None of them reach the exponential accuracy of polynomial or rational interpolation for smooth functions at well-chosen points.

Exercises

  1. Derive the tridiagonal system for the natural spline from the continuity of at the interior points.
  2. Show that the Hermite basis functions satisfy , , and the analogous conditions for the others.
  3. Compute the PCHIP and Akima end slopes for equally spaced data and show they agree. (This is why their errors coincide in the table.)
  4. Add a clamped end condition (known at the ends) to the spline and confirm fourth-order convergence for .
  5. Construct monotone data for which the Catmull-Rom spline is not monotone.
Hints and answers
  1. With second derivatives , continuity of at gives ; the natural condition sets .
  2. , so , and vanishes at and . The other three are checked the same way.
  3. Write the PCHIP end formula (a one-sided three-point slope estimate) and the Akima end rule for equal spacing and compare them; where they agree, the interior treatment is what remains to separate the two methods.
  4. Replace the first and last rows of the tridiagonal system by conditions; for the maximum error should now fall by about 16 each time is halved.
  5. Take a flat stretch next to a rise, such as at . The Catmull-Rom tangent at is , so on the curve with and a positive end slope dips below zero before returning, although the data never decrease.

Further reading

  • I. J. Schoenberg, “Contributions to the problem of approximation of equidistant data by analytic functions”, Quarterly of Applied Mathematics 4 (1946) 45–99 and 112–141.
  • C. de Boor, A Practical Guide to Splines, revised ed., Springer, 2001.
  • H. Akima, “A new method of interpolation and smooth curve fitting based on local procedures”, Journal of the ACM 17 (1970) 589–602.
  • F. N. Fritsch and R. E. Carlson, “Monotone piecewise cubic interpolation”, SIAM Journal on Numerical Analysis 17 (1980) 238–246.
  • E. Catmull and R. Rom, “A class of local interpolating splines”, in Computer Aided Geometric Design, Academic Press, 1974, 317–326.