Interpolation: from Lagrange to splines
Use the barycentric formula for efficient, stable polynomial interpolation and Chebyshev nodes to avoid the Runge phenomenon. Build cubic splines and PCHIP for tasks such as yield curves, trajectories and tabulated data.
After this lesson you can
- Derive the polynomial interpolation error and interpret the nodal polynomial.
- Implement barycentric interpolation at Chebyshev nodes and evaluate it in O(n) per point.
- Use the Lebesgue constant to explain and avoid Runge’s phenomenon.
- Construct natural and not-a-knot cubic splines by solving a tridiagonal system and compare them with PCHIP.
- Choose an interpolation method based on smoothness, monotonicity and extrapolation.
Before you start
Motivation: filling gaps between data
Interpolation constructs a function passing exactly through data and uses it between them. It seems like numerical computation’s most innocent problem and arises whenever a table lacks a needed value:
- Interest-rate curves. Markets quote bonds at 1, 2, 3, 5, 7, 10, 20 and 30 years. Discounting a cash flow at 4.3 years requires that maturity’s rate, and pricing a forward contract needs the forward rate , depending on the interpolated curve’s derivative. Two methods passing through the same points can give entirely different, even negative forwards; the second lab uses real U.S. Treasury data. This underlies the zero-coupon curve.
- Robot trajectories. A planner gives a few waypoints per joint. Straight segments produce discontinuous velocities, hence infinite acceleration at corners. A cubic spline gives continuous position, velocity and acceleration, needed for trajectory time parameterization.
- Tables of expensive functions. If evaluating costs an entire simulation, evaluate at a few well-chosen nodes and interpolate. With suitable nodes, a degree-160 polynomial reproduces Runge’s function to (we will measure it); this is the idea behind Chebfun.
This quick review corrects three common misconceptions. First, Lagrange’s formula is not “just theoretical”: its barycentric form is stable and costs per point. Second, the Runge phenomenon comes from nodes, not degree: with Chebyshev nodes degree 1000 works perfectly. Third, for data whose locations cannot be chosen (interest rates, experimental tables), use a cubic spline or, when shape matters, PCHIP, rather than a global polynomial.
Existence, uniqueness and the Vandermonde matrix
Proof
Uniqueness: if and interpolate, vanishes at distinct points, and a nonzero degree- polynomial has at most roots; hence . Existence: the problem is linear in coefficients and map , , is linear between spaces of equal dimension . It is injective as just shown, hence bijective.
∎Writing in the monomial basis turns the conditions into system with Vandermonde matrix , determinant . Algebra courses suggest this route, but numerically it is poor: columns increasingly resemble one another on (high even powers are all nearly in the center and at the edges), and is severely ill-conditioned. Beckermann (2000) proved that for any real nodes, grows at least exponentially with .
Be careful with the conclusion. Ill-conditioning of is a defect of the basis, not the problem. Interpolation has its own condition number, the Lebesgue constant as we will see, which is tiny for good nodes. The cell compares both.
import numpy as np
def cheb_points(n):
"""n + 1 puntos de Chebyshev (extremos de T_n), con la fórmula del seno: simétricos y con el 0 exacto."""
return np.sin(np.pi * (n - 2 * np.arange(n + 1)) / (2 * n))
def equi_points(n):
return np.linspace(-1.0, 1.0, n + 1)
def lebesgue_function(x, t):
"""lambda(t) = sum_j |l_j(t)| = |omega(t)| sum_j |w_j| / |t - x_j|: sin restas, sin cancelación."""
w = np.array([1.0 / np.prod(xj - np.delete(x, j)) for j, xj in enumerate(x)])
D = t[:, None] - x[None, :]
hit = (D == 0).any(axis=1)
D[hit] = 1.0 # en un nodo, lambda = 1
lam = np.abs(np.prod(D, axis=1)) * (np.abs(w) / np.abs(D)).sum(axis=1)
lam[hit] = 1.0
return lam
t = np.linspace(-1, 1, 20001)
print(" n cond(V) equi cond(V) Cheb Λ_n equi Λ_n Cheb")
for n in [5, 10, 20, 30, 40]:
kv = [np.linalg.cond(np.vander(pts(n), increasing=True)) for pts in (equi_points, cheb_points)]
lam_e = lebesgue_function(equi_points(n), t).max()
lam_c = lebesgue_function(cheb_points(n), t).max()
print(f"{n:2d} {kv[0]:11.2e} {kv[1]:11.2e} {lam_e:10.3e} {lam_c:7.3f}")The table separates two often-confused problems. With 41 Chebyshev points , yet those nodes’ Lebesgue constant is : the problem is well conditioned and the monomial basis spoils it. With 41 equally spaced nodes both fail: is of order (numerically singular, making the exact figure meaningless), and , so the problem itself amplifies data errors billions of times. Change basis to fix the first, nodes to fix the second.
Function lebesgue_function already uses the next section’s idea: write , a sum of positive terms without subtraction, evaluable accurately even when equals .
Lagrange and the barycentric formula
The Lagrange basis makes interpolation trivial. For each node, polynomial
equals 1 at and 0 at all other nodes, so interpolates without solving a system: the problem matrix in that basis is identity. Evaluated directly it costs per point and everything must be recomputed on adding a node. Textbooks therefore present it as a theoretical curiosity and recommend Newton divided differences. Berrut and Trefethen (2004) showed rewriting suffices.
Call , of degree , the nodal polynomial, and define barycentric weights as
Then and, factoring out the common factor,
Weights are computed once in , and each evaluation costs . Adding a node only updates weights in . An even better second form exists. Interpolating constant 1 gives exactly 1, so . Dividing the first form by this identity eliminates :
Three properties make this the working form:
- Weights matter only up to a common factor, which cancels between numerator and denominator. Classical families have closed formulas in : equally spaced nodes, ; Chebyshev points , with at both ends and elsewhere.
- It always interpolates, even with weight errors. For any the expression is rational and equals at (as , term dominates numerator and denominator). Weight rounding errors do not destroy interpolation.
- Evaluation near a node is safe. When is very close to , term is huge and computed with relative error from subtraction ; the same factor appears above and below and cancels. Only exact needs separate handling, as it would give . The final coding exercise asks you to do this.
Stability: Higham’s result
Higham (2004) analyzed rounding in both forms. The first is backward stable: the computed value is the exact interpolant of data with of order , where is unit roundoff from lesson 1. The second is not backward stable, but is forward stable with a bound proportional to Lebesgue constant : for nodes with small , such as Chebyshev nodes, its error is of the same order as unavoidable error. This is lesson 3’s backward/forward error distinction, and Higham concludes the second form can be appreciably worse than the first only with poor nodes. One practical exception: outside the node interval, when extrapolating, the second form loses this guarantee and the first is preferable (Webb, Trefethen and Gonnet, 2012).
Interpolation error
If data come from a smooth function, how far does deviate between nodes? The answer is one of numerical analysis’s most useful formulas.
The proof repeats a one-line argument times: construct an auxiliary function with zeros and repeatedly apply Rolle’s theorem. You will reconstruct it in the guided exercise. Notice the resemblance to Taylor’s Lagrange remainder, : the limiting case as all nodes merge at .
The formula separates error into two very different factors:
- depends on the function: how fast its derivatives grow. You do not control it.
- depends only on nodes. You do control those, and its shape is revealing.
Taking maxima gives . With equally spaced nodes is tiny in the center and huge near the ends: with 21 nodes, the end hump is tens of thousands of times the central one (the cell below gives the exact number). This difference contains the Runge phenomenon in embryo. Try reducing it.
You may discover two things. Move nodes toward the ends, since each node flattens neighboring humps and edge humps have neighbors on only one side. The minimum occurs when all humps have equal height: if one were higher, move a node toward it. This balanced distribution has a name and exact solution.
Runge, Lebesgue and Chebyshev
The Runge phenomenon
In 1901 Carl Runge published his eponymous example: on , an analytic, innocent-looking function interpolated at equally spaced nodes. As degree rises, the interpolant converges in the center and diverges near the ends with growing oscillations. This is the Runge phenomenon: equally spaced polynomial interpolation can diverge for smooth functions, even analytic throughout the interval.
The error formula alone cannot explain it. has poles at , so grows like , and bound diverges for both node types: even Chebyshev, where and grows like . The bound takes the worst derivative over the whole interval, is too pessimistic and does not distinguish nodes. The precise explanation uses Hermite’s integral formula and potential theory (Trefethen 2019, chapters 11–13): each node family has a complex-plane region that must leave singularity-free for interpolation to converge throughout . For Chebyshev nodes the region is the interval itself: need only be analytic in some neighborhood (quantified by the Bernstein ellipse theorem below). For equally spaced nodes it extends to on the imaginary axis, beyond Runge’s poles at .
There is a second reason, more serious in practice because it affects any function, illustrated by noise in the lab.
The Lebesgue constant
is the infinity norm of linear operator mapping data to interpolant: perturb data by with , and the interpolant changes by , of magnitude at most . The bound is attained: choose at point where is maximal. Thus is exactly interpolation’s absolute condition number with respect to data. It also controls approximation error:
Proof
Since reproduces degree- polynomials, . Then , and by the triangle inequality and , .
∎The implication matters: the interpolant is almost as good as the best polynomial, up to factor . If grows slowly, interpolation is nearly optimal. If it grows like , that factor overwhelms convergence and amplifies any data error by , including rounding of each . How does it grow? Classical theory in Trefethen (2019), chapter 15, gives
and for any choice of nodes grows at least like : Chebyshev nodes are within a constant of optimal. The cell checks this and measures noise amplification.
rng = np.random.default_rng(0)
runge = lambda x: 1 / (1 + 25 * x**2)
print(" n Λ_n equi 2^(n+1)/(e n ln n) Λ_n Cheb (2/π)ln(n+1)+1 Λ_n aleatorios")
for n in [10, 20, 30, 40]:
le = lebesgue_function(equi_points(n), t).max()
lc = lebesgue_function(cheb_points(n), t).max()
lr = lebesgue_function(np.sort(rng.uniform(-1, 1, n + 1)), t).max()
print(f"{n:2d} {le:9.3e} {2**(n + 1) / (np.e * n * np.log(n)):9.3e} {lc:6.3f} {2 / np.pi * np.log(n + 1) + 1:6.3f} {lr:9.3e}")
def interp(x, f, tt):
"""Segunda forma baricéntrica con pesos generales (en el laboratorio la construirás con calma)."""
w = np.array([1.0 / np.prod(xj - np.delete(x, j)) for j, xj in enumerate(x)])
D = tt[:, None] - x[None, :]
hit = (D == 0)
D[hit] = 1.0
C = w / D
p = (C @ f) / C.sum(axis=1)
fila, col = np.nonzero(hit)
p[fila] = f[col]
return p
eps = 1e-8
print(f"\nruido uniforme de amplitud {eps:.0e} en los datos de 1/(1 + 25x²):")
for n in [10, 20, 30, 40]:
for nombre, pts in [("equi", equi_points), ("Cheb", cheb_points)]:
x = pts(n)
p0 = interp(x, runge(x), t)
p1 = interp(x, runge(x) + eps * rng.uniform(-1, 1, n + 1), t)
print(f" n = {n:2d} {nombre}: ‖f - p‖ = {np.abs(runge(t) - p0).max():8.1e} ‖p_ruido - p‖/ε = {np.abs(p1 - p0).max() / eps:9.2e}")
# la cota se alcanza: delta_j = eps * signo(l_j(t*)) en el punto t* donde lambda es máxima
n = 20
x = equi_points(n)
lam = lebesgue_function(x, t)
ts = np.array([t[np.argmax(lam)]])
ell = np.array([interp(x, np.eye(n + 1)[j], ts)[0] for j in range(n + 1)])
print(f"\nn = 20 equi: Λ_n = {lam.max():.4e}; con el ruido en contra, |p_ruido(t*) - p(t*)|/ε = "
f"{abs(interp(x, eps * np.sign(ell), ts)[0]) / eps:.4e} en t* = {ts[0]:.4f}")All three claims hold. With equally spaced nodes multiplies by 368 to 711 every 10 degrees (the formula predicts factor apart from the ratio of ) and reaches 86 % of the asymptotic formula at (factor makes approximation improve slowly). With Chebyshev, , below bound . Uniform random nodes are worse than equally spaced ones ( in this sample): they leave large gaps, often near endpoints, with nothing clustering them where needed.
Noise amplification follows : with equally spaced nodes it rises from at to at , always below because random noise is not aligned with the worst case; with Chebyshev it stays between and . Adversarial noise gives amplification at exactly : the bound is attainable. Runge error with exact data tells the same story: it rises from to for equally spaced nodes and falls from to for Chebyshev.
Chebyshev nodes
Chebyshev nodes are projections onto of equally spaced points on the unit semicircle. Two families are common:
- Roots of : , . They exclude endpoints.
- Chebyshev points (extrema of ): , . They include , have barycentric weights , and are used by Chebfun.
Both cluster near endpoints with density proportional to , discovered by moving nodes, and both have logarithmic Lebesgue constants. Roots also exactly solve the figure’s problem.
Proof
By recurrence , has leading coefficient , so is monic. Since , alternately reaches at points , . Suppose monic of degree had . Then has degree (terms cancel) and at each has the sign of because . Thus changes sign times and has roots, which with degree forces and , a contradiction. If , the same argument with non-strict inequalities, counting zeros of with multiplicity, also gives zeros and : the optimum is unique. Since is monic of degree , , with equality exactly when , meaning nodes are roots of .
∎The proof explains the figure: the optimum equioscillates, all humps having equal height. The gain is huge:
for m in [11, 21]:
xe = np.linspace(-1, 1, m)
xc = np.cos((2 * np.arange(m) + 1) * np.pi / (2 * m)) # raíces de T_m
om_e = np.abs(np.prod(t[:, None] - xe[None, :], axis=1))
om_c = np.abs(np.prod(t[:, None] - xc[None, :], axis=1))
centro = np.abs(t) <= 0.1
print(f"{m} nodos: max|ω| equi = {om_e.max():.3e} (extremos/centro = {om_e.max() / om_e[centro].max():.0f}); "
f"raíces de T_{m}: {om_c.max():.4e}; 2^(1-{m}) = {2.0**(1 - m):.4e}")With 21 nodes, roots of attain exactly , while equally spaced nodes give : 245 times more. For equally spaced nodes the end hump is 54411 times the central one. In the error formula this means excellent interpolation in the center and poor at the edges, exactly as in the Runge lab.
Smoothness determines speed
Chebyshev-node interpolation converges for any minimally regular function, with speed determined by smoothness of . Two central theorems from Trefethen (2019):
- Functions with derivatives. If are absolutely continuous and has finite total variation , degree- Chebyshev interpolant error is at most : algebraic convergence (Theorem 7.2).
- Analytic functions. If is analytic inside Bernstein ellipse , with foci and semiaxes summing to , and there, error is at most : geometric convergence (Theorem 8.2).
For Runge’s function, the largest ellipse avoiding poles has minor semiaxis , and since Bernstein ellipse semiaxes are this gives . Each additional degree divides error by about . The first lab checks both theorems.
Lab 1: barycentric Chebyshev interpolation
Implement weights for arbitrary nodes, the closed Chebyshev formula and evaluation in per point, comparing against the Vandermonde approach.
from scipy.interpolate import BarycentricInterpolator
def bary_weights(x):
"""Pesos w_j = 1 / prod_{k != j} (x_j - x_k): O(n²), una sola vez por conjunto de nodos."""
x = np.asarray(x, dtype=float)
return np.array([1.0 / np.prod(xj - np.delete(x, j)) for j, xj in enumerate(x)])
def cheb_weights(n):
"""Pesos de los n + 1 puntos de Chebyshev en O(n): (-1)^j, con 1/2 en los extremos."""
w = (-1.0) ** np.arange(n + 1)
w[0] *= 0.5
w[-1] *= 0.5
return w
def bary_eval(x, w, f, tt):
"""Segunda forma baricéntrica: O(n) por punto. En un nodo devuelve el dato."""
tt = np.atleast_1d(np.asarray(tt, dtype=float))
D = tt[:, None] - x[None, :]
hit = (D == 0)
D[hit] = 1.0 # evita 0/0; esas filas se corrigen abajo
C = w / D
p = (C @ f) / C.sum(axis=1)
fila, col = np.nonzero(hit)
p[fila] = f[col]
return p
f = lambda x: 1 / (1 + 25 * x**2)
tt = np.linspace(-1, 1, 5001)
rho = (1 + np.sqrt(26)) / 5
print(" n Vandermonde baricéntrica rho^-n residuo de V c = f")
for n in [20, 40, 60, 80, 100]:
x = cheb_points(n)
V = np.vander(x, increasing=True)
c = np.linalg.solve(V, f(x))
err_v = np.abs(np.polynomial.polynomial.polyval(tt, c) - f(tt)).max()
err_b = np.abs(bary_eval(x, cheb_weights(n), f(x), tt) - f(tt)).max()
print(f"{n:4d} {err_v:9.2e} {err_b:9.2e} {rho**-n:8.2e} {np.abs(V @ c - f(x)).max():8.2e}")
x = cheb_points(40)
w_gen, w_cheb = bary_weights(x), cheb_weights(40)
print("\nn = 40: max |desde cero - scipy| =", np.abs(bary_eval(x, w_cheb, f(x), tt) - BarycentricInterpolator(x, f(x))(tt)).max())
print("pesos generales / pesos de Chebyshev: entre", (w_gen / w_cheb).min(), "y", (w_gen / w_cheb).max())
with np.errstate(all="ignore"):
w_ing = bary_weights(500 + 500 * cheb_points(299)) # 300 nodos en [0, 1000]
print("300 nodos en [0, 1000]: pesos calculados como 0:", int(np.sum(w_ing == 0)), "de", w_ing.size)Through both approaches have the same error because approximation error dominates, closely following . From Vandermonde stagnates around while barycentric error keeps falling to at . The last column is more troubling: the Vandermonde polynomial does not even pass through the data (residual at ). np.linalg.solve is backward stable, so residual is of order , and resulting coefficients are huge and cancel each other.
The scratch implementation matches SciPy to . General and Chebyshev-formula weights differ by constant factor , the common factor of exact Chebyshev-point weights, which cancels in the second form. The last line warns: with 300 nodes on , products overflow to inf and all 300 weights become zero. Scale is the cause: on an interval of length , those products grow like . Fixing it is part of the coding exercise.
Now convergence for three functions of decreasing smoothness: analytic, once continuously differentiable (, whose second derivative jumps at 0), and discontinuous.
import matplotlib.pyplot as plt
funcs = {
"1/(1 + 25x²): analítica": lambda x: 1 / (1 + 25 * x**2),
"x|x|: una derivada continua": lambda x: x * np.abs(x),
"signo(x): un salto": np.sign,
}
ns = np.array([10, 20, 40, 80, 160, 320, 640])
lejos = np.abs(tt) >= 0.1
for nombre, g in funcs.items():
errs, errs_lejos = [], []
for n in ns:
x = cheb_points(n)
e = np.abs(bary_eval(x, cheb_weights(n), g(x), tt) - g(tt))
errs.append(e.max())
errs_lejos.append(e[lejos].max())
errs = np.array(errs)
print(f"{nombre:30s}", " ".join(f"{v:.1e}" for v in errs))
if "salto" in nombre:
print(f"{' lejos del salto (|x| ≥ 0.1)':30s}", " ".join(f"{v:.1e}" for v in errs_lejos))
plt.loglog(ns, errs_lejos, "o-", label="signo(x), solo |x| ≥ 0.1")
else:
plt.loglog(ns, np.maximum(errs, 1e-17), "o-", label=nombre)
if "x|x|" in nombre:
print(f" pendiente log-log: {np.polyfit(np.log(ns), np.log(errs), 1)[0]:.3f}")
if "analítica" in nombre:
print(f" error dividido por grado, de n = 20 a 80: {(errs[1] / errs[3]) ** (1 / 60):.4f}; rho = {rho:.4f}")
plt.xlabel("grado n"); plt.ylabel("error máximo"); plt.legend(); plt.show()
n = 1000
x = cheb_points(n)
print(f"\n|x| con grado {n}: error máximo {np.abs(bary_eval(x, cheb_weights(n), np.abs(x), tt) - np.abs(tt)).max():.2e}")The three regimes are clear in the graph:
- Analytic: geometric convergence. Between and , each extra degree divides error by versus theoretical . At error is already and then stays at : it does not grow with degree, Higham stability in action.
- : and are absolutely continuous and has bounded variation, so the theorem gives , and measured slope is .
- Jump: maximum error cannot fall below 1: a polynomial is continuous while the function jumps from to , so near the jump it misses by at least 1. Away from the jump it converges, from to , but much more slowly than for the analytic function.
The final line interpolates at degree 1000 and obtains error , consistent with predicted by the theorem with . Degree 1000 causes no numerical problem; only the corner of limits accuracy.
Piecewise interpolation
Sometimes nodes are fixed: bond maturities, experimental times or image pixels are usually equally spaced or irregular. The answer is piecewise interpolation: a low-degree polynomial in each interval , joined with some smoothness. Error depends on spacing rather than degree.
Linear and cubic Hermite
Piecewise linear interpolation joins data by line segments. Applying the error formula with on each interval, and since ,
It is robust (never outside the data range), local (each datum affects only its two intervals), and only : the derivative jumps at each node.
If derivatives are also known, cubic Hermite interpolation uses the unique cubic matching endpoint values and slopes on each interval. It is and the error formula, counting each node twice, gives , hence . With the cubic is
with , , and . Derivatives are rarely known; the question is where to get them. Splines choose them for smoothness; PCHIP to preserve shape.
Cubic splines
Count conditions: cubics have unknowns; interpolating both ends of each interval gives equations, and continuity of and at the interior nodes gives more. Two remain, one per endpoint:
- Natural: .
- Clamped: and given.
- Not-a-knot: continuous at and , so the first two segments are the same cubic and is no longer a true knot (likewise at the other end). Default for SciPy’s
CubicSplineand MATLAB’sspline. - Periodic: and match at both ends.
For computation, convenient unknowns are moments . On each interval is linear, so with ,
Integrating twice and imposing and ,
This already interpolates and has continuous by construction. must still be continuous at each interior node. Differentiating, with the data slope,
and equating,
With natural conditions this is a tridiagonal, symmetric, strictly diagonally dominant system (), hence positive definite, and lesson 4’s Thomas algorithm solves it stably without pivoting in . The not-a-knot condition at is , a three-entry row eliminable to recover a tridiagonal system.
Why this smoothness? The name comes from draftsmen’s flexible rulers, wooden strips held by weights at waypoints; I. J. Schoenberg adopted it for these functions in 1946. The strip assumes minimum bending energy, and the natural spline does likewise with its linear approximation, :
Proof
Let , vanishing at every node. Then , and it suffices to show the cross term vanishes. Integrating by parts on each interval, . Summing over telescopes boundary terms (because and are continuous), leaving by natural conditions. On each interval is constant , so . Hence .
∎For accuracy, clamped and not-a-knot splines of have error (constant for clamped, Hall and Meyer 1976), Hermite’s order without requiring derivatives. Natural splines instead impose , false for almost any , paying for this at endpoints where convergence is only . The lab measures it.
Spline versus global polynomial
What changes when one datum moves? For methods linear in data (polynomial and splines), response to is cardinal function : the interpolant of data . For the global polynomial it is , not small anywhere. For splines, moments of far from satisfy homogeneous recurrence (equally spaced nodes), whose bounded solution decays geometrically with alternating sign. An exercise computes the factor.
Three conclusions from the figure. Polynomial influence does not decay: moving data at one end changes the other, and step data produce Runge oscillations (nodes are equally spaced). Spline influence decays by roughly a fixed factor per interval: initially the influence of on is for natural versus for polynomial. It is almost local, but not local (not-a-knot decays somewhat less near boundaries). PCHIP influence is exactly zero beyond the third interval because enters only slopes , and . Both splines overshoot: in the monotone table, segment just before the jump drops almost to 0 although data rise from to (overshoot for natural and for not-a-knot), because continuity of forces a “run-up”. Their derivative reaches , and not-a-knot also drops below 0 and rises above 1 at the ends. If these were distribution data both would give negative density, and not-a-knot probabilities outside .
PCHIP: preserving shape
Fritsch and Carlson (1980) addressed monotone data requiring a monotone interpolant. Their answer is piecewise cubic Hermite (therefore only ), choosing slopes to preserve shape. With and on an interval with , they proved the cubic is monotone if and pair lies in a region containing square . Their recipe:
- If and have opposite signs or either is 0, datum is a local extremum (or flat segment): .
- Otherwise averages the two neighboring slopes, never exceeding three times the smaller. Fritsch and Butland’s version (1984), used by
scipy.interpolate.PchipInterpolator, takes the weighted harmonic mean
- At endpoints, use a three-point formula corrected to avoid the wrong sign or exceeding .
The resulting Piecewise Cubic Hermite Interpolating Polynomial satisfies the curve lies between and on each interval: on monotone intervals by Fritsch and Carlson’s theorem, around local extrema because the slope is 0. It never overshoots data. It pays twice: it is only , and for smooth data is less accurate than splines ( versus in the lab) and flattens extrema. In the smooth-data figure PCHIP visibly flattens peaks. It suits tabulated distribution functions, discount curves, concentration profiles and quantities that must not oscillate; neural spline flows use the same idea, splines monotone by construction, for invertibility.
Lab 2: splines from scratch and a yield curve
First, the natural spline with Thomas’s algorithm versus CubicSpline, and convergence of the four piecewise methods on over .
from scipy.interpolate import CubicSpline, PchipInterpolator
def thomas(a, b, c, d):
"""Sistema tridiagonal (lección 4): a subdiagonal (n-1), b diagonal (n), c superdiagonal (n-1)."""
n = len(b)
cp, dp = np.zeros(n), np.zeros(n)
cp[0], dp[0] = (c[0] / b[0] if n > 1 else 0.0), d[0] / b[0]
for i in range(1, n):
piv = b[i] - a[i - 1] * cp[i - 1]
cp[i] = c[i] / piv if i < n - 1 else 0.0
dp[i] = (d[i] - a[i - 1] * dp[i - 1]) / piv
x = np.zeros(n)
x[-1] = dp[-1]
for i in range(n - 2, -1, -1):
x[i] = dp[i] - cp[i] * x[i + 1]
return x
def natural_spline(x, y):
"""Momentos M_i = s''(x_i) del spline natural: M_0 = M_n = 0 y el sistema tridiagonal interior."""
h = np.diff(x)
delta = np.diff(y) / h
M = np.zeros(len(x))
M[1:-1] = thomas(h[1:-1], 2 * (h[:-1] + h[1:]), h[1:-1], 6 * np.diff(delta))
return M
def spline_eval(x, y, M, t):
i = np.clip(np.searchsorted(x, t, side="right") - 1, 0, len(x) - 2)
h = x[i + 1] - x[i]
a, b = x[i + 1] - t, t - x[i]
return (M[i] * a**3 + M[i + 1] * b**3) / (6 * h) + (y[i] / h - M[i] * h / 6) * a + (y[i + 1] / h - M[i + 1] * h / 6) * b
rng = np.random.default_rng(1)
x = np.sort(np.r_[0.0, rng.uniform(0, 10, 18), 10.0]) # nodos no equiespaciados
y = np.sin(x) + 0.1 * x
t10 = np.linspace(0, 10, 3001)
print(f"max |desde cero - CubicSpline(natural)| = {np.abs(spline_eval(x, y, natural_spline(x, y), t10) - CubicSpline(x, y, bc_type='natural')(t10)).max():.1e}")
f = np.exp
t01 = np.linspace(0, 1, 20001)
print("\n N lineal natural not-a-knot PCHIP")
prev = None
for N in [10, 20, 40, 80, 160]:
x = np.linspace(0, 1, N + 1)
e = [np.abs(np.interp(t01, x, f(x)) - f(t01)).max(),
np.abs(spline_eval(x, f(x), natural_spline(x, f(x)), t01) - f(t01)).max(),
np.abs(CubicSpline(x, f(x))(t01) - f(t01)).max(),
np.abs(PchipInterpolator(x, f(x))(t01) - f(t01)).max()]
print(f"{N:4d} " + " ".join(f"{v:9.2e}" for v in e))
if prev is not None:
print(" orden " + " ".join(f"{np.log2(p / q):9.2f}" for p, q in zip(prev, e)))
prev = e
x = np.linspace(0, 1, 41)
err = np.abs(spline_eval(x, f(x), natural_spline(x, f(x)), t01) - f(t01))
centro = (t01 > 0.25) & (t01 < 0.75)
print(f"\nnatural, N = 40: error en [0.25, 0.75] = {err[centro].max():.1e}; error máximo (junto a los extremos) = {err.max():.1e}")The scratch spline matches CubicSpline(bc_type="natural") to on irregular nodes. Measured orders match theory: 2 for linear, 4 for not-a-knot and 3 for PCHIP. Natural remains order 2; the last line explains why: at its error is , on par with not-a-knot, but near endpoints reaches . This boundary layer comes from imposing on a function with .
Now the yield curve. Data are U.S. Treasury yields for December 2, 2021, published at home.treasury.gov, maturities 1 month to 30 years. They are par yields, not zero-coupon rates; to focus on interpolation we treat them as continuously compounded zero rates , a simplification (conversion is bootstrapping the zero-coupon curve). Discount factor is and instantaneous forward . A negative forward means paying to lend between and ; nothing like that occurred that day: all rates were positive and the average 20-to-30-year forward, ratio , was too.
# Curva del Tesoro de EE. UU., 2 de diciembre de 2021 (rendimientos en %), home.treasury.gov
plazos = np.array([1/12, 2/12, 3/12, 6/12, 1, 2, 3, 5, 7, 10, 20, 30])
tipos = np.array([0.05, 0.05, 0.05, 0.09, 0.27, 0.63, 0.90, 1.21, 1.38, 1.44, 1.87, 1.76]) / 100
T = np.linspace(plazos[0], 30, 6001)
metodos = {
"spline natural sobre r(t)": CubicSpline(plazos, tipos, bc_type="natural"),
"spline not-a-knot sobre r(t)": CubicSpline(plazos, tipos),
"PCHIP sobre r(t)": PchipInterpolator(plazos, tipos),
}
print("forward instantáneo f(t) = r(t) + t r'(t)")
for nombre, s in metodos.items():
fwd = s(T) + T * s(T, 1)
k = np.argmin(fwd)
plt.plot(T, 100 * fwd, label=nombre)
print(f" {nombre:30s} mínimo {100 * fwd[k]:7.3f} % en t = {T[k]:5.2f}; f(30) = {100 * fwd[-1]:7.3f} %")
# lineal en t r(t) = -log P(t): forward constante en cada tramo, el cociente de la tabla
fwd_tramos = np.diff(plazos * tipos) / np.diff(plazos)
print(f" lineal en -log P(t), por tramos: mínimo {100 * fwd_tramos.min():.3f} %; de 20 a 30 años {100 * fwd_tramos[-1]:.3f} %")
plt.step(plazos, 100 * np.r_[fwd_tramos, fwd_tramos[-1]], where="post", color="gray", label="lineal en -log P (por tramos)")
plt.axhline(0, color="black", lw=0.8)
plt.xlabel("plazo t (años)"); plt.ylabel("forward instantáneo (%)"); plt.legend(); plt.show()All three interpolants pass through the same twelve points and are barely distinguishable when plotting . Their forwards differ. The key datum is the 20-year yield (1.87 %) exceeds the 30-year yield (1.76 %). Not-a-knot joins segments and into one cubic, arriving at 30 years with such a negative slope that instantaneous forward is while the 20-to-30-year average is . Natural gives at 30 years and PCHIP ; both stay positive throughout, with minima and at short maturities. Linear interpolation of gives piecewise-constant forwards, positive whenever grows, but jumping at each node.
The lesson is that a forward is a derivative, and differentiation amplifies differences between interpolants invisible in their values. Curve construction therefore uses methods designed for positive, reasonable forwards, such as Hagan and West’s monotone convex (2006), rather than a library’s default spline, and extrapolates beyond the last maturity using an explicit rule.
Grid interpolation: bilinear
Many tables have two or more inputs: a volatility surface by strike and maturity, an image by row and column, a thermodynamic table by pressure and temperature. On a grid by the simplest interpolation uses a tensor product: linearly in along two rows, then linearly in between results (order does not matter). In cell with local coordinates ,
This is bilinear interpolation. Each weight is the area of the rectangle opposite its corner; all four are nonnegative and sum to 1, so the result is a weighted average, never outside the corner range. Expanding gives with : linear along either axis but not linear overall. Along diagonal it is a parabola, and contours are hyperbolas.
Error is , as for one-variable linear interpolation; the interpolant is continuous but not differentiable across cell boundaries. This underlies bilinear image resizing, torch.nn.functional.interpolate(mode="bilinear") and grid_sample, and feature sampling in RoIAlign. In dimensions multilinear interpolation combines cell vertices: cheap in 2 or 3 dimensions, infeasible in 20, an aspect of the curse of dimensionality. Bicubic interpolation uses a grid of neighbors and gains an order of smoothness.
from scipy.interpolate import RegularGridInterpolator
pts = np.random.default_rng(2).uniform([0, -1], [2, 1], size=(1000, 2))
gx, gy = np.linspace(0, 2, 5), np.linspace(-1, 1, 9)
X, Y = np.meshgrid(gx, gy, indexing="ij")
g = lambda x, y: 1 + 2 * x - 3 * y + 0.5 * x * y
print("bilineal sobre a + bx + cy + dxy, error máximo:",
np.abs(RegularGridInterpolator((gx, gy), g(X, Y))(pts) - g(pts[:, 0], pts[:, 1])).max())
h2 = lambda x, y: np.sin(3 * x) * np.cos(2 * y)
print("\n celdas lineal cúbica (por defecto) cúbica (rtol = 1e-12)")
for k in [8, 16, 32, 64]:
gx, gy = np.linspace(0, 2, k + 1), np.linspace(-1, 1, k + 1)
X, Y = np.meshgrid(gx, gy, indexing="ij")
exacto = h2(pts[:, 0], pts[:, 1])
e_lin = np.abs(RegularGridInterpolator((gx, gy), h2(X, Y))(pts) - exacto).max()
e_cub = np.abs(RegularGridInterpolator((gx, gy), h2(X, Y), method="cubic")(pts) - exacto).max()
e_cub2 = np.abs(RegularGridInterpolator((gx, gy), h2(X, Y), method="cubic", solver_args={"rtol": 1e-12})(pts) - exacto).max()
print(f"{k:3d} x {k:<3d} {e_lin:9.2e} {e_cub:9.2e} {e_cub2:9.2e}")Bilinear exactly reproduces (error ), and for a smooth function error falls by about 4 whenever resolution doubles: order 2. Cubic gains two orders, but the table hides a trap: with 64 cells per side and default settings its error () is worse than at 32. For method="cubic", RegularGridInterpolator solves coefficients iteratively, and default tolerance eventually dominates error; requesting solver_args={"rtol": 1e-12} reduces error to and restores order 4. If a convergence table flattens, check tolerances first.
The professional version
| Need | Tool | Notes |
|---|---|---|
| Polynomial at chosen nodes | BarycentricInterpolator(x, y) | second barycentric form; use Chebyshev nodes |
| Approximate a function to machine precision | Chebfun (MATLAB), numpy.polynomial.Chebyshev.interpolate | Chebyshev interpolation; Chebfun chooses degree adaptively, NumPy uses the requested degree |
| Smooth curve through fixed data | CubicSpline(x, y, bc_type=...) | 'not-a-knot' default; 'natural', 'clamped', 'periodic' |
| Data that must not oscillate | PchipInterpolator(x, y) | piecewise monotone, ; Akima1DInterpolator is a local alternative without monotonicity guarantee |
| Splines of any degree | make_interp_spline(x, y, k) | B-spline basis (de Boor) |
| Fast 1D linear | np.interp(t, x, y) | returns endpoint value outside range, no extrapolation |
| -dimensional grids | RegularGridInterpolator(puntos, valores, method=...) | 'linear', 'nearest', 'cubic', 'pchip'… |
| Scattered data | griddata, RBFInterpolator | triangulation or radial functions |
Two SciPy documentation details matter. interp1d is marked a legacy API: it will not receive improvements and the classes above are recommended. Most classes extrapolate by default (extrapolate=True), extending the last segment’s polynomial, while interp1d raises an out-of-range error unless fill_value="extrapolate" is requested and np.interp retains the endpoint value. Three functions with the same purpose and three different out-of-data behaviors:
from scipy.interpolate import interp1d
x = np.linspace(0, 10, 11)
y = np.sin(x)
ts = [11.0, 12.0, 15.0]
print("t ", " ".join(f"{v:8.2f}" for v in ts))
print("sin(t) ", " ".join(f"{v:8.3f}" for v in np.sin(ts)))
print("CubicSpline ", " ".join(f"{v:8.3f}" for v in CubicSpline(x, y)(ts)))
print("Pchip ", " ".join(f"{v:8.3f}" for v in PchipInterpolator(x, y)(ts)))
print("np.interp ", " ".join(f"{v:8.3f}" for v in np.interp(ts, x, y)))
try:
interp1d(x, y, kind="cubic")(11.0)
except ValueError as err:
print("interp1d cúbico:", err)Inside the range the three methods resemble one another; outside, 5 units beyond the last datum, CubicSpline returns for a function bounded by 1, PCHIP returns , np.interp repeats the last value and interp1d refuses. None knows what lies beyond the data.
Common mistakes
Connections and further reading
- The next lesson, function approximation, turns the Chebyshev interpolant into a Chebyshev series computable by FFT, and studies best minimax approximation from the Lebesgue inequality. Quadrature integrates interpolants: Newton–Cotes integrates equally spaced ones (inheriting their problems), Clenshaw–Curtis Chebyshev ones.
- Finance. Yield curves and volatility surfaces interpolate under no-arbitrage constraints (positive forwards, option prices convex in strike); Hagan and West (2006) compare common yield-curve methods.
- Robotics. Joint trajectories use cubic or quintic splines for continuous velocity and acceleration.
- Vision. Image resizing, region alignment (RoIAlign) and adapting ViT position embeddings to another resolution (position interpolation) use bilinear or bicubic interpolation.
- Machine learning. Noiseless Gaussian process regression interpolates with a kernel rather than polynomials, and overparameterized models’ interpolation regime (benign overfitting) poses another version of when exactly fitting data is appropriate.
- Reading. Berrut and Trefethen (2004) on barycentric interpolation; Trefethen, Approximation Theory and Approximation Practice (2019), chapters 5–15, for theory with code; de Boor (2001) on splines; Fritsch and Carlson (1980) on PCHIP.
Exercises
Step 1 of 4. What auxiliary function do you construct?
barycentric_weights(x) and barycentric_eval(x, w, f, t). Weights may have any common factor but must be finite and nonzero even for 300 nodes on , where the naive product exceeds float64 range. barycentric_eval uses the second form, accepts scalar t (returning a scalar) or an array, returns exactly f[j] when t equals a node, and must not divide by zero or produce nan. The starter code is the naive version: it passes some tests but not all.import numpy as np
def barycentric_weights(x):
"""Pesos baricéntricos w_j = 1 / prod_{k != j} (x_j - x_k), salvo un factor común."""
x = np.asarray(x, dtype=float)
return np.array([1.0 / np.prod(xj - np.delete(x, j)) for j, xj in enumerate(x)])
def barycentric_eval(x, w, f, t):
"""Interpolante en t (escalar o array) por la segunda forma baricéntrica."""
x, w, f = (np.asarray(v, dtype=float) for v in (x, w, f))
t = np.atleast_1d(np.asarray(t, dtype=float))
C = w / (t[:, None] - x[None, :])
return (C @ f) / C.sum(axis=1)np.polyfit(x, y, 20). What reasons argue against it? Select all correct answers.More than one answer may be correct.
More than one answer may be correct.
Summary
- The degree- interpolant through distinct nodes exists and is unique. Computing it with a Vandermonde matrix is poor because of the basis, not the problem.
- Barycentric formula: weights in (or with closed forms), evaluation in ; the first form is backward stable and the second forward stable for nodes with small .
- Error: . The node factor is minimized by roots of , equioscillating at height .
- is interpolation’s condition number and the factor in Lebesgue’s inequality: with equally spaced nodes, with Chebyshev.
- With Chebyshev, smoothness sets speed: with derivatives and for analytic functions.
- Cubic splines: , tridiagonal moment system, error for not-a-knot or clamped and near natural-spline boundaries. PCHIP: , never overshoots data. Bilinear: weighted average of four corners with area weights.