TExcelTAD
Home › Numerical Methods › Cubic Splines

Cubic Splines

A cubic spline uses a cubic polynomial on each interval, joined so that the function, its first derivative and its second derivative are all continuous. The result looks smooth to the eye, converges at fourth order, and avoids the oscillations of high-degree polynomials. Splines are the standard tool for smooth interpolation, from data curves to font outlines and animation paths.

Conditions

With n+1n + 1 nodes there are nn cubics and 4n4n coefficients. The conditions are:

  • interpolation at both ends of each piece: 2n2n equations;
  • continuity of S′S' and S′′S'' at the n−1n - 1 interior nodes: 2(n−1)2(n - 1) equations.

That leaves two conditions free, which are fixed at the ends:

End condition Meaning
natural S′′(t0)=S′′(tn)=0S''(t_0) = S''(t_n) = 0
clamped S′S' prescribed at both ends
not-a-knot S′′′S''' continuous at the second and second-to-last nodes (SciPy's default)
periodic S,S′,S′′S, S', S'' match at both ends

The tridiagonal system

Using the second derivatives Mk=S′′(tk)M_k = S''(t_k) as unknowns, the continuity of S′S' gives for each interior node (equal spacing hh):

Mk−1+4Mk+Mk+1=6h2(yk−1−2yk+yk+1),M_{k-1} + 4M_k + M_{k+1} = \frac{6}{h^2}\left(y_{k-1} - 2y_k + y_{k+1}\right),

a tridiagonal, diagonally dominant system solved in O(n)O(n) (Banded and Positive Definite Matrices).

python · try it yourself
import numpy as np
from scipy.interpolate import CubicSpline
from scipy.linalg import solve_banded

def natural_spline_M(t, y):
    n = len(t) - 1
    h = t[1] - t[0]                                   # equal spacing for simplicity
    rhs = 6 / h**2 * (y[:-2] - 2 * y[1:-1] + y[2:])
    ab = np.zeros((3, n - 1)); ab[0, 1:] = 1; ab[1] = 4; ab[2, :-1] = 1
    M = np.zeros(n + 1)
    M[1:-1] = solve_banded((1, 1), ab, rhs)
    return M

def spline_eval(t, y, M, x):
    h = t[1] - t[0]
    k = np.clip(np.searchsorted(t, x) - 1, 0, len(t) - 2)
    a, b = t[k + 1] - x, x - t[k]
    return (M[k] * a**3 + M[k + 1] * b**3) / (6 * h) + (y[k] / h - M[k] * h / 6) * a + (y[k + 1] / h - M[k + 1] * h / 6) * b

t = np.linspace(0, 4, 9)
y = np.sin(t)
M = natural_spline_M(t, y)
x = np.array([0.3, 1.7, 3.1])
print("ours :", np.round(spline_eval(t, y, M, x), 10))
print("SciPy:", np.round(CubicSpline(t, y, bc_type="natural")(x), 10))
ours : [0.2954861  0.9915473  0.04061254]
SciPy: [0.2954861  0.9915473  0.04061254]

Accuracy

For a smooth ff, a clamped or not-a-knot spline has error O(h4)O(h^4). The natural condition forces S′′=0S'' = 0 at the ends, which is wrong unless f′′f'' vanishes there, and that drops accuracy to O(h2)O(h^2) near the ends.

python · try it yourself
import numpy as np
from scipy.interpolate import CubicSpline

f = np.exp
xx = np.linspace(0, 2, 20001)
print("   n   not-a-knot    natural      linear")
for n in (10, 20, 40, 80):
    t = np.linspace(0, 2, n + 1)
    e1 = np.max(np.abs(CubicSpline(t, f(t))(xx) - f(xx)))
    e2 = np.max(np.abs(CubicSpline(t, f(t), bc_type="natural")(xx) - f(xx)))
    e3 = np.max(np.abs(np.interp(xx, t, f(t)) - f(xx)))
    print(f"{n:4d}   {e1:.2e}    {e2:.2e}    {e3:.2e}")
   n   not-a-knot    natural      linear
  10   2.72e-04    1.44e-02    3.35e-02
  20   1.88e-05    3.62e-03    8.79e-03
  40   1.24e-06    9.07e-04    2.25e-03
  80   7.95e-08    2.27e-04    5.70e-04

Halving hh divides the not-a-knot error by about 16 (fourth order) and the natural spline's error by about 4 (second order, from the ends).

Overshoot and monotone alternatives

Cubic splines can overshoot near sharp changes in data. When the data are monotone and must stay so (cumulative distributions, dose-response curves), use a monotone piecewise cubic such as PchipInterpolator or Akima1DInterpolator, which give up C2C^2 continuity to avoid overshoot.

python · try it yourself
import numpy as np
from scipy.interpolate import CubicSpline, PchipInterpolator

t = np.array([0.0, 1, 2, 3, 4, 5])
y = np.array([0.0, 0, 0, 1, 1, 1])                   # a step
xx = np.linspace(0, 5, 501)
print(f"cubic spline range: [{CubicSpline(t, y)(xx).min():.3f}, {CubicSpline(t, y)(xx).max():.3f}]")
print(f"PCHIP range       : [{PchipInterpolator(t, y)(xx).min():.3f}, {PchipInterpolator(t, y)(xx).max():.3f}]")
cubic spline range: [-0.128, 1.128]
PCHIP range       : [0.000, 1.000]

In software

  • scipy.interpolate.CubicSpline (with bc_type), make_interp_spline (any degree, B-spline form), UnivariateSpline / make_smoothing_spline (smoothing noisy data instead of interpolating).
  • Bézier curves and B-splines in graphics, fonts (TrueType uses quadratic and PostScript/OpenType cubic Béziers) and CAD (NURBS) are relatives of the same idea.

Exercises

Exercise 1: Count the unknowns

A spline on 11 nodes has how many cubic pieces and how many coefficients?

Answer

10 pieces, 40 coefficients.

Solution

n=10n = 10 intervals, 4 coefficients each. Interpolation gives 20 equations, continuity of S′S' and S′′S'' at 9 interior nodes gives 18, and the end conditions give the last 2.

Exercise 2: Natural spline error

Why does a natural spline approximate exe^x less accurately near the ends than a clamped one?

Answer

It forces S′′=0S'' = 0 at the ends, but (ex)′′=ex≠0(e^x)'' = e^x \ne 0.

Solution

The wrong end condition introduces an O(h2)O(h^2) error that decays away from the ends; clamped or not-a-knot conditions keep O(h4)O(h^4).

Exercise 3: Spline derivatives (code)

Use CubicSpline through sin⁡t\sin t at 21 points on [0,π][0, \pi] to estimate cos⁡(1)\cos(1) from the spline's derivative.

Answer

The spline gives 0.5402860.540286 against cos⁡1≈0.540302\cos 1 \approx 0.540302, an error of about 2×10−52 \times 10^{-5} (derivatives of a spline converge one order slower than the spline itself).

Solution
python · try it yourself
import numpy as np
from scipy.interpolate import CubicSpline
t = np.linspace(0, np.pi, 21)
S = CubicSpline(t, np.sin(t))
print(f"{float(S(1.0, 1)):.8f} {np.cos(1.0):.8f} error {abs(float(S(1.0, 1)) - np.cos(1.0)):.1e}")
0.54028574 0.54030231 error 1.7e-05

Test yourself

A cubic spline is continuous in…

  1. SS only
  2. SS and S′S'
  3. SS, S′S' and S′′S''
  4. all derivatives

The error of a not-a-knot cubic spline for smooth ff is…

  1. O(h)O(h)
  2. O(h2)O(h^2)
  3. O(h4)O(h^4)
  4. O(h8)O(h^8)

Computing a cubic spline requires solving…

  1. a dense system
  2. a tridiagonal system
  3. an eigenvalue problem
  4. nothing