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 nodes there are cubics and coefficients. The conditions are:
- interpolation at both ends of each piece: equations;
- continuity of and at the interior nodes: equations.
That leaves two conditions free, which are fixed at the ends:
| End condition | Meaning |
|---|---|
| natural | |
| clamped | prescribed at both ends |
| not-a-knot | continuous at the second and second-to-last nodes (SciPy's default) |
| periodic | match at both ends |
The tridiagonal system
Using the second derivatives as unknowns, the continuity of gives for each interior node (equal spacing ):
a tridiagonal, diagonally dominant system solved in (Banded and Positive Definite Matrices).
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 , a clamped or not-a-knot spline has error . The natural condition forces at the ends, which is wrong unless vanishes there, and that drops accuracy to near the ends.
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 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 continuity to avoid overshoot.
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(withbc_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
intervals, 4 coefficients each. Interpolation gives 20 equations, continuity of and 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 less accurately near the ends than a clamped one?
Answer
It forces at the ends, but .
Solution
The wrong end condition introduces an error that decays away from the ends; clamped or not-a-knot conditions keep .
Exercise 3: Spline derivatives (code)
Use CubicSpline through at 21 points on to estimate from the spline's derivative.
Answer
The spline gives against , an error of about (derivatives of a spline converge one order slower than the spline itself).
Solution
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…
- only
- and
- , and
- all derivatives
The error of a not-a-knot cubic spline for smooth is…
Computing a cubic spline requires solving…
- a dense system
- a tridiagonal system
- an eigenvalue problem
- nothing