Module contents
Lesson 9 of 26Review 80 min

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 (xj,fj)(x_j, f_j) 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 f(t)=r(t)+t r′(t)f(t) = r(t) + t\,r'(t), 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 ff 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 10−1410^{-14} (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 O(n)\bigO(n) 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 pp and qq interpolate, p−q∈Pnp - q \in \mathcal{P}_n vanishes at n+1n + 1 distinct points, and a nonzero degree-≤n\le n polynomial has at most nn roots; hence p=qp = q. Existence: the problem is linear in coefficients and map Pn→Rn+1\mathcal{P}_n \to \R^{n+1}, p↦(p(x0),…,p(xn))p \mapsto (p(x_0), \dots, p(x_n)), is linear between spaces of equal dimension n+1n + 1. It is injective as just shown, hence bijective.

∎

Writing p(x)=c0+c1x+⋯+cnxnp(x) = c_0 + c_1 x + \cdots + c_n x^n in the monomial basis turns the conditions into system Vc=f\mat{V}\vb{c} = \vb{f} with Vandermonde matrix vjk=xjkv_{jk} = x_j^k, determinant ∏i<j(xj−xi)≠0\prod_{i < j}(x_j - x_i) \neq 0. Algebra courses suggest this route, but numerically it is poor: columns 1,x,x2,…1, x, x^2, \dots increasingly resemble one another on [−1,1][-1, 1] (high even powers are all nearly 00 in the center and 11 at the edges), and V\mat{V} is severely ill-conditioned. Beckermann (2000) proved that for any real nodes, κ2(V)\kappa_2(\mat{V}) grows at least exponentially with nn.

Be careful with the conclusion. Ill-conditioning of V\mat{V} is a defect of the basis, not the problem. Interpolation has its own condition number, the Lebesgue constant Λn\Lambda_n as we will see, which is tiny for good nodes. The cell compares both.

[ ]Vandermonde versus actual problem conditioningBrowser
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 κ(V)≈7.8×1014\kappa(\mat{V}) \approx 7.8\times 10^{14}, yet those nodes’ Lebesgue constant is 3.313.31: the problem is well conditioned and the monomial basis spoils it. With 41 equally spaced nodes both fail: κ(V)\kappa(\mat{V}) is of order 101810^{18} (numerically singular, making the exact figure meaningless), and Λ40≈4.7×109\Lambda_{40} \approx 4.7\times 10^{9}, 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 λ(t)=∣ω(t)∣∑j∣wj∣/∣t−xj∣\lambda(t) = \abs{\omega(t)}\sum_j \abs{w_j}/\abs{t - x_j}, a sum of positive terms without subtraction, evaluable accurately even when λ\lambda equals 102010^{20}.

Lagrange and the barycentric formula

The Lagrange basis makes interpolation trivial. For each node, polynomial

ℓj(x)=∏k≠jx−xkxj−xk\ell_j(x) = \prod_{k \neq j} \frac{x - x_k}{x_j - x_k}

equals 1 at xjx_j and 0 at all other nodes, so p(x)=∑jfj ℓj(x)p(x) = \sum_j f_j\,\ell_j(x) interpolates without solving a system: the problem matrix in that basis is identity. Evaluated directly it costs O(n2)\bigO(n^2) 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 ω(x)=∏k=0n(x−xk)\omega(x) = \prod_{k=0}^{n}(x - x_k), of degree n+1n + 1, the nodal polynomial, and define barycentric weights as

wj=1∏k≠j(xj−xk),j=0,…,n.w_j = \frac{1}{\prod_{k \neq j}(x_j - x_k)}, \qquad j = 0, \dots, n.

Then ℓj(x)=ω(x) wjx−xj\ell_j(x) = \omega(x)\,\dfrac{w_j}{x - x_j} and, factoring out the common factor,

p(x)=ω(x)∑j=0nwjx−xj fj(primera forma).p(x) = \omega(x) \sum_{j=0}^{n} \frac{w_j}{x - x_j}\, f_j \qquad \text{(primera forma)}.

Weights are computed once in O(n2)\bigO(n^2), and each evaluation costs O(n)\bigO(n). Adding a node only updates weights in O(n)\bigO(n). An even better second form exists. Interpolating constant 1 gives exactly 1, so 1=ω(x)∑jwj/(x−xj)1 = \omega(x)\sum_j w_j/(x - x_j). Dividing the first form by this identity eliminates ω(x)\omega(x):

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 O(n)\bigO(n): equally spaced nodes, wj=(−1)j(nj)w_j = (-1)^j\binom{n}{j}; n+1n + 1 Chebyshev points xj=cos⁡(jπ/n)x_j = \cos(j\pi/n), wj=(−1)jδjw_j = (-1)^j\delta_j with δj=1/2\delta_j = 1/2 at both ends and 11 elsewhere.
  • It always interpolates, even with weight errors. For any wj≠0w_j \neq 0 the expression is rational and equals fjf_j at xjx_j (as x→xjx \to x_j, term jj dominates numerator and denominator). Weight rounding errors do not destroy interpolation.
  • Evaluation near a node is safe. When xx is very close to xjx_j, term wj/(x−xj)w_j/(x - x_j) is huge and computed with relative error from subtraction x−xjx - x_j; the same factor appears above and below and cancels. Only exact x=xjx = x_j needs separate handling, as it would give 0/00/0. 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 fj(1+ηj)f_j(1 + \eta_j) with ∣ηj∣\abs{\eta_j} of order n un\,u, where uu is unit roundoff from lesson 1. The second is not backward stable, but is forward stable with a bound proportional to Lebesgue constant Λn\Lambda_n: for nodes with small Λn\Lambda_n, 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 pp deviate between nodes? The answer is one of numerical analysis’s most useful formulas.

The proof repeats a one-line argument n+1n + 1 times: construct an auxiliary function with n+2n + 2 zeros and repeatedly apply Rolle’s theorem. You will reconstruct it in the guided exercise. Notice the resemblance to Taylor’s Lagrange remainder, f(n+1)(ξ)(x−x0)n+1/(n+1)!f^{(n+1)}(\xi)(x - x_0)^{n+1}/(n + 1)!: the limiting case as all nodes merge at x0x_0.

The formula separates error into two very different factors:

  1. f(n+1)(ξ)/(n+1)!f^{(n+1)}(\xi)/(n + 1)! depends on the function: how fast its derivatives grow. You do not control it.
  2. ω(x)\omega(x) depends only on nodes. You do control those, and its shape is revealing.

Taking maxima gives ∥f−p∥∞≤∥f(n+1)∥∞∥ω∥∞/(n+1)!\norm{f - p}_\infty \le \norm{f^{(n+1)}}_\infty \norm{\omega}_\infty / (n + 1)!. With equally spaced nodes ∣ω∣\abs{\omega} 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.

InteractiveMove the nodes
−1−0.500.510.04380.01060.005650.005650.01060.0438
  • ∣ω(x)∣=∏j∣x−xj∣|\omega(x)| = \prod_j |x - x_j|
  • tallest lobe
7
max⁡[−1,1]∣ω(x)∣\max_{[-1,1]} |\omega(x)|0.0438
With equally spaced nodes0.0438
Your best resultmove a node
Tallest / shortest lobe7.75
The tallest lobe is 7.8 times the shortest. Lower the maximum by moving a node toward the red one.
Drag the mm nodes along the axis to minimize the maximum of ∣ω(x)∣\abs{\omega(x)}. They start equally spaced: end humps are much higher than central ones, and the highest is red. Which way should nodes move? What do humps look like once you cannot improve further? When ready, select Reveal Chebyshev.

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: f(x)=1/(1+25x2)f(x) = 1/(1 + 25x^2) on [−1,1][-1, 1], 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.

InteractiveThe Runge lab
−0.500.511.5−1−0.50.51
Log scale: error ∣f(x)−p(x)∣|f(x) - p(x)| and Lebesgue function λ(x)=∑j∣ℓj(x)∣\lambda(x) = \sum_j |\ell_j(x)|
10⁻⁶10⁻⁴10⁻²10⁰10²−1−0.500.51
  • f(x)=1/(1+25x2)f(x) = 1/(1 + 25x^2)
  • interpolant pp and nodes
  • error ∣f−p∣|f - p|
  • Lebesgue function λ(x)\lambda(x)
Nodes
12
1e−6
Lebesgue constant Λn\Lambda_n89.3
Error ∥f−p∥∞\|f - p\|_\infty without noise3.66
Equally spaced nodes: Λn≈89.3\Lambda_n \approx 89.3. The interpolant oscillates near the ends and increasing degree worsens error.
Interpolation of f(x)=1/(1+25x2)f(x) = 1/(1 + 25x^2) with n+1n + 1 nodes. Below, log-scale error ∣f−p∣\abs{f - p} and Lebesgue function λ(x)\lambda(x). Increase degree with equally spaced nodes: where does error grow? Switch to Chebyshev at the same degree. Try random nodes too. Then enable data noise: compare measured amplification with Λn\Lambda_n for each node family and see which curve error follows.

The error formula alone cannot explain it. ff has poles at ±i/5\pm i/5, so ∥f(n+1)∥∞\norm{f^{(n+1)}}_\infty grows like (n+1)! 5n+1(n + 1)!\,5^{n+1}, and bound ∥f(n+1)∥∞∥ω∥∞/(n+1)!≈5n+1∥ω∥∞\norm{f^{(n+1)}}_\infty\norm{\omega}_\infty/(n + 1)! \approx 5^{n+1}\norm{\omega}_\infty diverges for both node types: even Chebyshev, where ∥ω∥∞=2−n\norm{\omega}_\infty = 2^{-n} and 5n+12−n5^{n+1}2^{-n} grows like 2.5n2.5^n. 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 ff must leave singularity-free for interpolation to converge throughout [−1,1][-1, 1]. For Chebyshev nodes the region is the interval itself: ff need only be analytic in some neighborhood (quantified by the Bernstein ellipse theorem below). For equally spaced nodes it extends to ±0.526i\pm 0.526i on the imaginary axis, beyond Runge’s poles at ±0.2i\pm 0.2i.

There is a second reason, more serious in practice because it affects any function, illustrated by noise in the lab.

The Lebesgue constant

Λn\Lambda_n is the infinity norm of linear operator InI_n mapping data to interpolant: perturb data by δj\delta_j with ∣δj∣≤ε\abs{\delta_j} \le \eps, and the interpolant changes by ∑jδjℓj(x)\sum_j \delta_j \ell_j(x), of magnitude at most ε λ(x)≤εΛn\eps\,\lambda(x) \le \eps\Lambda_n. The bound is attained: choose δj=ε signo⁡(ℓj(x∗))\delta_j = \eps\,\operatorname{signo}(\ell_j(x^\ast)) at point x∗x^\ast where λ\lambda is maximal. Thus Λn\Lambda_n is exactly interpolation’s absolute condition number with respect to data. It also controls approximation error:

Proof

Since InI_n reproduces degree-≤n\le n polynomials, Inp∗=p∗I_n p^\ast = p^\ast. Then f−Inf=(f−p∗)−In(f−p∗)f - I_n f = (f - p^\ast) - I_n(f - p^\ast), and by the triangle inequality and ∥Ing∥∞≤Λn∥g∥∞\norm{I_n g}_\infty \le \Lambda_n \norm{g}_\infty, ∥f−Inf∥∞≤∥f−p∗∥∞+Λn∥f−p∗∥∞\norm{f - I_n f}_\infty \le \norm{f - p^\ast}_\infty + \Lambda_n\norm{f - p^\ast}_\infty.

∎

The implication matters: the interpolant is almost as good as the best polynomial, up to factor 1+Λn1 + \Lambda_n. If Λn\Lambda_n grows slowly, interpolation is nearly optimal. If it grows like 2n2^n, that factor overwhelms convergence and amplifies any data error by 2n2^n, including rounding u≈1.1×10−16u \approx 1.1\times 10^{-16} of each fjf_j. How does it grow? Classical theory in Trefethen (2019), chapter 15, gives

Λnequi∼2n+1e nlog⁡n,ΛnCheb≤2πlog⁡(n+1)+1,\Lambda_n^{\text{equi}} \sim \frac{2^{n+1}}{e\,n\log n}, \qquad \Lambda_n^{\text{Cheb}} \le \frac{2}{\pi}\log(n + 1) + 1,

and for any choice of nodes Λn\Lambda_n grows at least like 2πlog⁡n\tfrac{2}{\pi}\log n: Chebyshev nodes are within a constant of optimal. The cell checks this and measures noise amplification.

[ ]Lebesgue constants and noise amplificationBrowser
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 Λn\Lambda_n multiplies by 368 to 711 every 10 degrees (the formula predicts factor 210=10242^{10} = 1024 apart from the ratio of nlog⁡nn\log n) and reaches 86 % of the asymptotic formula at n=40n = 40 (factor log⁡n\log n makes approximation improve slowly). With Chebyshev, Λ40=3.31\Lambda_{40} = 3.31, below bound 3.363.36. Uniform random nodes are worse than equally spaced ones (Λ10≈9.8×103\Lambda_{10} \approx 9.8\times 10^3 in this sample): they leave large gaps, often near endpoints, with nothing clustering them where needed.

Noise amplification follows Λn\Lambda_n: with equally spaced nodes it rises from 1010 at n=10n = 10 to 6.6×1086.6\times 10^{8} at n=40n = 40, always below Λn\Lambda_n because random noise is not aligned with the worst case; with Chebyshev it stays between 1.11.1 and 1.51.5. Adversarial noise δj=ε signo⁡(ℓj(t∗))\delta_j = \eps\,\operatorname{signo}(\ell_j(t^\ast)) gives amplification at t∗=−0.9749t^\ast = -0.9749 exactly Λ20=1.0987×104\Lambda_{20} = 1.0987\times 10^4: the bound is attainable. Runge error with exact data tells the same story: it rises from 1.91.9 to 10510^5 for equally spaced nodes and falls from 0.130.13 to 3.4×10−43.4\times 10^{-4} for Chebyshev.

Chebyshev nodes

Chebyshev nodes are projections onto [−1,1][-1, 1] of equally spaced points on the unit semicircle. Two families are common:

  • Roots of Tm(x)=cos⁡(marccos⁡x)T_{m}(x) = \cos(m \arccos x): xk=cos⁡((2k+1)π/(2m))x_k = \cos\big((2k + 1)\pi/(2m)\big), k=0,…,m−1k = 0, \dots, m - 1. They exclude endpoints.
  • Chebyshev points (extrema of TnT_n): xj=cos⁡(jπ/n)x_j = \cos(j\pi/n), j=0,…,nj = 0, \dots, n. They include ±1\pm 1, have barycentric weights (−1)jδj(-1)^j\delta_j, and are used by Chebfun.

Both cluster near endpoints with density proportional to 1/1−x21/\sqrt{1 - x^2}, discovered by moving nodes, and both have logarithmic Lebesgue constants. Roots also exactly solve the figure’s problem.

Proof

By recurrence Tm+1=2xTm−Tm−1T_{m+1} = 2xT_m - T_{m-1}, TmT_m has leading coefficient 2m−12^{m-1}, so T~=21−mTm\tilde T = 2^{1-m}T_m is monic. Since Tm(cos⁡θ)=cos⁡(mθ)T_m(\cos\theta) = \cos(m\theta), T~\tilde T alternately reaches ±21−m\pm 2^{1-m} at m+1m + 1 points yk=cos⁡(kπ/m)y_k = \cos(k\pi/m), k=0,…,mk = 0, \dots, m. Suppose monic qq of degree mm had ∥q∥∞<21−m\norm{q}_\infty < 2^{1-m}. Then r=T~−qr = \tilde T - q has degree ≤m−1\le m - 1 (terms xmx^m cancel) and at each yky_k has the sign of T~(yk)\tilde T(y_k) because ∣q(yk)∣<∣T~(yk)∣\abs{q(y_k)} < \abs{\tilde T(y_k)}. Thus rr changes sign mm times and has mm roots, which with degree ≤m−1\le m - 1 forces r≡0r \equiv 0 and q=T~q = \tilde T, a contradiction. If ∥q∥∞=21−m\norm{q}_\infty = 2^{1-m}, the same argument with non-strict inequalities, counting zeros of rr with multiplicity, also gives mm zeros and r≡0r \equiv 0: the optimum is unique. Since ω\omega is monic of degree mm, max⁡∣ω∣≥21−m\max\abs{\omega} \ge 2^{1-m}, with equality exactly when ω=T~\omega = \tilde T, meaning nodes are roots of TmT_m.

∎

The proof explains the figure: the optimum equioscillates, all humps having equal height. The gain is huge:

[ ]Nodal polynomial: equally spaced versus ChebyshevBrowser
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 T21T_{21} attain exactly 2−20≈9.54×10−72^{-20} \approx 9.54\times 10^{-7}, while equally spaced nodes give 2.34×10−42.34\times 10^{-4}: 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 ff. Two central theorems from Trefethen (2019):

  • Functions with ν\nu derivatives. If f,f′,…,f(ν−1)f, f', \dots, f^{(\nu-1)} are absolutely continuous and f(ν)f^{(\nu)} has finite total variation VV, degree-n>νn > \nu Chebyshev interpolant error is at most 4Vπν(n−ν)ν\dfrac{4V}{\pi\nu(n - \nu)^{\nu}}: algebraic convergence O(n−ν)\bigO(n^{-\nu}) (Theorem 7.2).
  • Analytic functions. If ff is analytic inside Bernstein ellipse EρE_\rho, with foci ±1\pm 1 and semiaxes summing to ρ>1\rho > 1, and ∣f∣≤M\abs{f} \le M there, error is at most 4Mρ−nρ−1\dfrac{4M\rho^{-n}}{\rho - 1}: geometric convergence (Theorem 8.2).

For Runge’s function, the largest ellipse avoiding poles ±i/5\pm i/5 has minor semiaxis 1/51/5, and since Bernstein ellipse semiaxes are (ρ±ρ−1)/2(\rho \pm \rho^{-1})/2 this gives ρ=1/5+1+1/25=(1+26)/5≈1.2198\rho = 1/5 + \sqrt{1 + 1/25} = (1 + \sqrt{26})/5 \approx 1.2198. Each additional degree divides error by about 1.221.22. The first lab checks both theorems.

Lab 1: barycentric Chebyshev interpolation

Implement weights for arbitrary nodes, the closed Chebyshev formula and evaluation in O(n)\bigO(n) per point, comparing against the Vandermonde approach.

[ ]The barycentric formula from scratchBrowser
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 n=40n = 40 both approaches have the same error because approximation error dominates, closely following ρ−n\rho^{-n}. From n=60n = 60 Vandermonde stagnates around 3×10−33\times 10^{-3} while barycentric error keeps falling to 2.3×10−92.3\times 10^{-9} at n=100n = 100. The last column is more troubling: the Vandermonde polynomial does not even pass through the data (residual 2.8×10−32.8\times 10^{-3} at n=100n = 100). np.linalg.solve is backward stable, so residual is of order u ∥V∥∥c∥u\,\norm{\mat{V}}\norm{\vb{c}}, and resulting coefficients c\vb{c} are huge and cancel each other.

The scratch implementation matches SciPy to 10−1510^{-15}. General and Chebyshev-formula weights differ by constant factor 1.374×1010=239/401.374\times 10^{10} = 2^{39}/40, the common factor 2n−1/n2^{n-1}/n of exact Chebyshev-point weights, which cancels in the second form. The last line warns: with 300 nodes on [0,1000][0, 1000], products ∏k≠j(xj−xk)\prod_{k\neq j}(x_j - x_k) overflow to inf and all 300 weights become zero. Scale is the cause: on an interval of length LL, those products grow like (L/4)n(L/4)^n. Fixing it is part of the coding exercise.

Now convergence for three functions of decreasing smoothness: analytic, once continuously differentiable (x∣x∣x\abs{x}, whose second derivative jumps at 0), and discontinuous.

[ ]Convergence by smoothnessBrowser
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 n=20n = 20 and n=80n = 80, each extra degree divides error by 1.21951.2195 versus theoretical ρ=1.2198\rho = 1.2198. At n=160n = 160 error is already 1.5×10−141.5\times 10^{-14} and then stays at 3×10−153\times 10^{-15}: it does not grow with degree, Higham stability in action.
  • x∣x∣x\abs{x}: ff and f′f' are absolutely continuous and f′′=2signo⁡(x)f'' = 2\operatorname{signo}(x) has bounded variation, so the theorem gives O(n−2)\bigO(n^{-2}), and measured slope is −2.003-2.003.
  • Jump: maximum error cannot fall below 1: a polynomial is continuous while the function jumps from −1-1 to 11, so near the jump it misses by at least 1. Away from the jump it converges, from 0.570.57 to 3.8×10−43.8\times 10^{-4}, but much more slowly than for the analytic function.

The final line interpolates ∣x∣\abs{x} at degree 1000 and obtains error 6×10−46\times 10^{-4}, consistent with O(1/n)\bigO(1/n) predicted by the theorem with ν=1\nu = 1. Degree 1000 causes no numerical problem; only the corner of ∣x∣\abs{x} 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 [xi,xi+1][x_i, x_{i+1}], joined with some smoothness. Error depends on spacing h=max⁡i(xi+1−xi)h = \max_i (x_{i+1} - x_i) rather than degree.

Linear and cubic Hermite

Piecewise linear interpolation joins data by line segments. Applying the error formula with n=1n = 1 on each interval, and since ∣(x−xi)(x−xi+1)∣≤h2/4\abs{(x - x_i)(x - x_{i+1})} \le h^2/4,

∥f−s∥∞≤h28∥f′′∥∞.\norm{f - s}_\infty \le \frac{h^2}{8}\norm{f''}_\infty.

It is robust (never outside the data range), local (each datum affects only its two intervals), and only C0C^0: the derivative jumps at each node.

If derivatives f′(xi)f'(x_i) are also known, cubic Hermite interpolation uses the unique cubic matching endpoint values and slopes on each interval. It is C1C^1 and the error formula, counting each node twice, gives f(4)(ξ)(x−xi)2(x−xi+1)2/4!f^{(4)}(\xi)(x - x_i)^2(x - x_{i+1})^2/4!, hence ∥f−s∥∞≤h4384∥f(4)∥∞\norm{f - s}_\infty \le \tfrac{h^4}{384}\norm{f^{(4)}}_\infty. With t=(x−xi)/ht = (x - x_i)/h the cubic is

s(x)=h00(t) yi+h10(t) h di+h01(t) yi+1+h11(t) h di+1,s(x) = h_{00}(t)\,y_i + h_{10}(t)\,h\,d_i + h_{01}(t)\,y_{i+1} + h_{11}(t)\,h\,d_{i+1},

with h00=(1+2t)(1−t)2h_{00} = (1 + 2t)(1 - t)^2, h10=t(1−t)2h_{10} = t(1 - t)^2, h01=t2(3−2t)h_{01} = t^2(3 - 2t) and h11=t2(t−1)h_{11} = t^2(t - 1). Derivatives are rarely known; the question is where to get them. Splines choose them for smoothness; PCHIP to preserve shape.

Cubic splines

Count conditions: nn cubics have 4n4n unknowns; interpolating both ends of each interval gives 2n2n equations, and continuity of s′s' and s′′s'' at the n−1n - 1 interior nodes gives 2(n−1)2(n - 1) more. Two remain, one per endpoint:

  • Natural: s′′(a)=s′′(b)=0s''(a) = s''(b) = 0.
  • Clamped: s′(a)s'(a) and s′(b)s'(b) given.
  • Not-a-knot: s′′′s''' continuous at x1x_1 and xn−1x_{n-1}, so the first two segments are the same cubic and x1x_1 is no longer a true knot (likewise at the other end). Default for SciPy’s CubicSpline and MATLAB’s spline.
  • Periodic: s′s' and s′′s'' match at both ends.

For computation, convenient unknowns are moments Mi=s′′(xi)M_i = s''(x_i). On each interval s′′s'' is linear, so with hi=xi+1−xih_i = x_{i+1} - x_i,

s′′(x)=Mi xi+1−xhi+Mi+1 x−xihi.s''(x) = M_i\,\frac{x_{i+1} - x}{h_i} + M_{i+1}\,\frac{x - x_i}{h_i}.

Integrating twice and imposing s(xi)=yis(x_i) = y_i and s(xi+1)=yi+1s(x_{i+1}) = y_{i+1},

s(x)=Mi(xi+1−x)3+Mi+1(x−xi)36hi+(yihi−Mihi6)(xi+1−x)+(yi+1hi−Mi+1hi6)(x−xi).s(x) = \frac{M_i (x_{i+1} - x)^3 + M_{i+1}(x - x_i)^3}{6h_i} + \Big(\frac{y_i}{h_i} - \frac{M_i h_i}{6}\Big)(x_{i+1} - x) + \Big(\frac{y_{i+1}}{h_i} - \frac{M_{i+1}h_i}{6}\Big)(x - x_i).

This ss already interpolates and has continuous s′′s'' by construction. s′s' must still be continuous at each interior node. Differentiating, with δi=(yi+1−yi)/hi\delta_i = (y_{i+1} - y_i)/h_i the data slope,

s′(xi+)=δi−hi3Mi−hi6Mi+1,s′(xi−)=δi−1+hi−16Mi−1+hi−13Mi,s'(x_i^+) = \delta_i - \frac{h_i}{3}M_i - \frac{h_i}{6}M_{i+1}, \qquad s'(x_i^-) = \delta_{i-1} + \frac{h_{i-1}}{6}M_{i-1} + \frac{h_{i-1}}{3}M_i,

and equating,

hi−1Mi−1+2(hi−1+hi)Mi+hiMi+1=6(δi−δi−1),i=1,…,n−1.h_{i-1}M_{i-1} + 2(h_{i-1} + h_i)M_i + h_i M_{i+1} = 6(\delta_i - \delta_{i-1}), \qquad i = 1, \dots, n - 1.

With natural conditions M0=Mn=0M_0 = M_n = 0 this is a tridiagonal, symmetric, strictly diagonally dominant system (2(hi−1+hi)>hi−1+hi2(h_{i-1} + h_i) > h_{i-1} + h_i), hence positive definite, and lesson 4’s Thomas algorithm solves it stably without pivoting in O(n)\bigO(n). The not-a-knot condition at x1x_1 is (M1−M0)/h0=(M2−M1)/h1(M_1 - M_0)/h_0 = (M_2 - M_1)/h_1, 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, ∫(s′′)2\int (s'')^2:

Proof

Let e=g−se = g - s, vanishing at every node. Then ∫(g′′)2=∫(s′′)2+2∫s′′e′′+∫(e′′)2\int (g'')^2 = \int (s'')^2 + 2\int s''e'' + \int (e'')^2, and it suffices to show the cross term vanishes. Integrating by parts on each interval, ∫xixi+1s′′e′′=[s′′e′]xixi+1−∫xixi+1s′′′e′\int_{x_i}^{x_{i+1}} s''e'' = \big[s''e'\big]_{x_i}^{x_{i+1}} - \int_{x_i}^{x_{i+1}} s'''e'. Summing over ii telescopes boundary terms (because s′′s'' and e′e' are continuous), leaving s′′(b)e′(b)−s′′(a)e′(a)=0s''(b)e'(b) - s''(a)e'(a) = 0 by natural conditions. On each interval s′′′s''' is constant cic_i, so ∫xixi+1s′′′e′=ci(e(xi+1)−e(xi))=0\int_{x_i}^{x_{i+1}} s'''e' = c_i\big(e(x_{i+1}) - e(x_i)\big) = 0. Hence ∫(g′′)2=∫(s′′)2+∫(e′′)2≥∫(s′′)2\int (g'')^2 = \int(s'')^2 + \int (e'')^2 \ge \int (s'')^2.

∎

For accuracy, clamped and not-a-knot splines of f∈C4f \in C^4 have error O(h4)\bigO(h^4) (constant 5/3845/384 for clamped, Hall and Meyer 1976), Hermite’s order without requiring derivatives. Natural splines instead impose s′′(a)=s′′(b)=0s''(a) = s''(b) = 0, false for almost any ff, paying for this at endpoints where convergence is only O(h2)\bigO(h^2). The lab measures it.

Spline versus global polynomial

What changes when one datum moves? For methods linear in data (polynomial and splines), response to yk→yk+1y_k \to y_k + 1 is cardinal function CkC_k: the interpolant of data (0,…,1,…,0)(0, \dots, 1, \dots, 0). For the global polynomial it is ℓk\ell_k, not small anywhere. For splines, moments of CkC_k far from kk satisfy homogeneous recurrence Mi−1+4Mi+Mi+1=0M_{i-1} + 4M_i + M_{i+1} = 0 (equally spaced nodes), whose bounded solution decays geometrically with alternating sign. An exercise computes the factor.

InteractiveSpline versus global polynomial
Influence of y4y_{4} on each interval: max⁡∣∂s/∂y4∣\max |\partial s / \partial y_{4}| (log scale)
10⁰10⁻¹10⁻²10⁻³10⁻⁴001234567
  • degree 7 polynomial
  • spline natural
  • spline not-a-knot
  • PCHIP
Overshoot: degree 7 polynomial0.507
Overshoot: spline natural0.046
Overshoot: spline not-a-knot0.047
Overshoot: PCHIP0
Influence of y4y_{4} on [0, 1]: degree 7 polynomial1.21
Influence of y4y_{4} on [0, 1]: spline natural0.0119
Influence of y4y_{4} on [0, 1]: spline not-a-knot0.0442
Influence of y4y_{4} on [0, 1]: PCHIP0
Overshoot measures how far the curve leaves [min⁡(yi,yi+1),max⁡(yi,yi+1)][\min(y_i, y_{i+1}), \max(y_i, y_{i+1})] on each segment. PCHIP always gives 0.
Eight vertically draggable data points and four interpolants: degree-7 polynomial, natural spline, not-a-knot spline and PCHIP; gray bands mark extrapolation. Below, on a logarithmic scale, the influence of the last moved datum on each interval. Move a central point: how far does its effect reach for each method? Inspect overshoot readings with monotone, step and peak data. Which method always respects data shape and what does it cost for smooth data?

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 y4y_4 on [0,1][0, 1] is 0.0120.012 for natural versus 1.211.21 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 yky_k enters only slopes dk−1d_{k-1}, dkd_k and dk+1d_{k+1}. Both splines overshoot: in the monotone table, segment [2,3][2, 3] just before the jump drops almost to 0 although data rise from 0.050.05 to 0.10.1 (overshoot 0.0460.046 for natural and 0.0470.047 for not-a-knot), because continuity of s′′s'' forces a “run-up”. Their derivative reaches −0.11-0.11, 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 [0,1][0, 1].

PCHIP: preserving shape

Fritsch and Carlson (1980) addressed monotone data requiring a monotone interpolant. Their answer is piecewise cubic Hermite (therefore only C1C^1), choosing slopes did_i to preserve shape. With αi=di/δi\alpha_i = d_i/\delta_i and βi=di+1/δi\beta_i = d_{i+1}/\delta_i on an interval with δi≠0\delta_i \neq 0, they proved the cubic is monotone if αi,βi≥0\alpha_i, \beta_i \ge 0 and pair (αi,βi)(\alpha_i, \beta_i) lies in a region containing square [0,3]2[0, 3]^2. Their recipe:

  1. If δi−1\delta_{i-1} and δi\delta_i have opposite signs or either is 0, datum ii is a local extremum (or flat segment): di=0d_i = 0.
  2. Otherwise did_i 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
w1+w2di=w1δi−1+w2δi,w1=2hi+hi−1,w2=hi+2hi−1.\frac{w_1 + w_2}{d_i} = \frac{w_1}{\delta_{i-1}} + \frac{w_2}{\delta_i}, \qquad w_1 = 2h_i + h_{i-1}, \quad w_2 = h_i + 2h_{i-1}.
  1. At endpoints, use a three-point formula corrected to avoid the wrong sign or exceeding 3δ3\delta.

The resulting Piecewise Cubic Hermite Interpolating Polynomial satisfies the curve lies between yiy_i and yi+1y_{i+1} 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 C1C^1, and for smooth data is less accurate than splines (O(h3)\bigO(h^3) versus O(h4)\bigO(h^4) 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 f(x)=exf(x) = e^x over [0,1][0, 1].

[ ]Natural cubic spline from scratchBrowser
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 9×10−169\times 10^{-16} 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 [0.25,0.75][0.25, 0.75] its error is 2.1×10−92.1\times 10^{-9}, on par with not-a-knot, but near endpoints reaches 8.3×10−58.3\times 10^{-5}. This boundary layer comes from imposing s′′(0)=s′′(1)=0s''(0) = s''(1) = 0 on a function with f′′=exf'' = e^x.

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 r(t)r(t), a simplification (conversion is bootstrapping the zero-coupon curve). Discount factor is P(t)=e−r(t)tP(t) = e^{-r(t)t} and instantaneous forward f(t)=− ⁣d ⁣dtlog⁡P(t)=r(t)+t r′(t)f(t) = -\tfrac{\dd}{\dd t}\log P(t) = r(t) + t\,r'(t). A negative forward means paying to lend between tt and t+ ⁣dtt + \dd t; nothing like that occurred that day: all rates were positive and the average 20-to-30-year forward, ratio (30 r30−20 r20)/10(30\,r_{30} - 20\,r_{20})/10, was too.

[ ]Implied forwards from a real yield curveBrowser
# 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 r(t)r(t). 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 [10,20][10, 20] and [20,30][20, 30] into one cubic, arriving at 30 years with such a negative slope that instantaneous forward is −1.104 %-1.104\,\% while the 20-to-30-year average is +1.540 %+1.540\,\%. Natural gives 0.846 %0.846\,\% at 30 years and PCHIP 0.770 %0.770\,\%; both stay positive throughout, with minima 0.048 %0.048\,\% and 0.050 %0.050\,\% at short maturities. Linear interpolation of −log⁡P-\log P gives piecewise-constant forwards, positive whenever t r(t)t\,r(t) 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 x0<⋯<xmx_0 < \cdots < x_m by y0<⋯<yny_0 < \cdots < y_n the simplest interpolation uses a tensor product: linearly in xx along two rows, then linearly in yy between results (order does not matter). In cell [xi,xi+1]×[yj,yj+1][x_i, x_{i+1}]\times[y_j, y_{j+1}] with local coordinates s,t∈[0,1]s, t \in [0, 1],

p(s,t)=(1−s)(1−t) f00+s(1−t) f10+(1−s) t f01+s t f11.p(s, t) = (1 - s)(1 - t)\,f_{00} + s(1 - t)\,f_{10} + (1 - s)\,t\,f_{01} + s\,t\,f_{11}.

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 p=a+bs+ct+d stp = a + bs + ct + d\,st with d=f00−f10−f01+f11d = f_{00} - f_{10} - f_{01} + f_{11}: linear along either axis but not linear overall. Along diagonal s=ts = t it is a parabola, and contours are hyperbolas.

InteractiveThe bilinear cell
0.100.900.600.20
Corner values
0.10
0.90
0.60
0.20
Weight of f00f_{00} (opposite area)0.245
Weight of f10f_{10} (opposite area)0.105
Weight of f01f_{01} (opposite area)0.455
Weight of f11f_{11} (opposite area)0.195
f(P)f(P): sum of weight times value0.431
Cross-term coefficient d xyd\,xy−1.20
On the diagonal, f(t,t)f(t, t) at t=0.5t = 0.50.450
Mean of f00f_{00} and f11f_{11} (what a linear function gives)0.150
With d≠0d \neq 0 the interpolant is not linear: it is linear along each axis, but its contours are hyperbolas.
Drag PP across the cell. Each corner's weight is the area of the opposite rectangle, shown in its color. The background shows interpolant contours. At the center of the dashed diagonal, compare the bilinear value with the average of its endpoints. What must the four values satisfy for contours to be straight lines?

Error is O(h2)\bigO(h^2), 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 dd dimensions multilinear interpolation combines 2d2^d cell vertices: cheap in 2 or 3 dimensions, infeasible in 20, an aspect of the curse of dimensionality. Bicubic interpolation uses a grid of 4×44\times 4 neighbors and gains an order of smoothness.

[ ]Bilinear and cubic on a gridBrowser
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 a+bx+cy+dxya + bx + cy + dxy (error 2×10−152\times 10^{-15}), 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 (1.77×10−51.77\times 10^{-5}) 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 7.1×10−77.1\times 10^{-7} and restores order 4. If a convergence table flattens, check tolerances first.

The professional version

NeedToolNotes
Polynomial at chosen nodesBarycentricInterpolator(x, y)second barycentric form; use Chebyshev nodes
Approximate a function to machine precisionChebfun (MATLAB), numpy.polynomial.Chebyshev.interpolateChebyshev interpolation; Chebfun chooses degree adaptively, NumPy uses the requested degree
Smooth curve through fixed dataCubicSpline(x, y, bc_type=...)'not-a-knot' default; 'natural', 'clamped', 'periodic'
Data that must not oscillatePchipInterpolator(x, y)piecewise monotone, C1C^1; Akima1DInterpolator is a local alternative without monotonicity guarantee
Splines of any degreemake_interp_spline(x, y, k)B-spline basis (de Boor)
Fast 1D linearnp.interp(t, x, y)returns endpoint value outside range, no extrapolation
dd-dimensional gridsRegularGridInterpolator(puntos, valores, method=...)'linear', 'nearest', 'cubic', 'pchip'…
Scattered datagriddata, RBFInterpolatortriangulation 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:

[ ]Outside the data rangeBrowser
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 13.9713.97 for a function bounded by 1, PCHIP returns −3.99-3.99, 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

ProofThe error formula via Rolle's theorem
Prove: Let f∈Cn+1[a,b]f \in C^{n+1}[a, b], distinct x0,…,xn∈[a,b]x_0, \dots, x_n \in [a, b], interpolant p∈Pnp \in \mathcal{P}_n and ω(t)=∏k=0n(t−xk)\omega(t) = \prod_{k=0}^{n}(t - x_k). For every x∈[a,b]x \in [a, b] there exists ξ\xi in the smallest interval JJ containing xx and the nodes such that f(x)−p(x)=f(n+1)(ξ) ω(x)/(n+1)!f(x) - p(x) = f^{(n+1)}(\xi)\,\omega(x)/(n + 1)!.
0
If xx is a node, both sides are 0 and any ξ\xi works. Assume xx is not a node, so ω(x)≠0\omega(x) \neq 0.

Step 1 of 4. What auxiliary function do you construct?

NumericThe Chebyshev nodal polynomial
Choose the 10 roots of T10T_{10} as nodes on [−1,1][-1, 1]. What is max⁡x∈[−1,1]∣ω(x)∣=max⁡∏k=110∣x−xk∣\max_{x \in [-1,1]} \abs{\omega(x)} = \max \prod_{k=1}^{10}\abs{x - x_k}?
CodeRobust barycentric interpolation
Implement 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 [0,1000][0, 1000], 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)
Shift+Enter to run
QuizWhy not degree-20 polyfit?
You have 21 equally spaced measurements of a smooth quantity on [−1,1][-1, 1] and someone proposes interpolation with np.polyfit(x, y, 20). What reasons argue against it? Select all correct answers.

More than one answer may be correct.

QuizInterpolating a distribution function
A distribution function FF is tabulated at 15 unequally spaced points, strictly increasing in the data. You need intermediate values and a continuous nonnegative density F′F' throughout. Which method guarantees this for any such data?
NumericHow many intervals?
You interpolate sin⁡x\sin x on [0,π][0, \pi] piecewise linearly with NN equal intervals. Using the linear interpolation error bound, what is the smallest NN guaranteeing maximum error ≤10−6\le 10^{-6}?
QuizThe natural spline boundary
You interpolate exe^x on [0,1][0, 1] with a natural spline and 41 equally spaced nodes. Error is order 10−910^{-9} on [0.25,0.75][0.25, 0.75] but nearly 10−410^{-4} near endpoints. Which changes restore O(h4)\bigO(h^4) error throughout? Select all correct answers.

More than one answer may be correct.

NumericHow local is a spline?
With integer nodes and many data, move one datum yky_k. Far from kk, change moments satisfy Mi−1+4Mi+Mi+1=0M_{i-1} + 4M_i + M_{i+1} = 0, and the non-exploding solution is geometric. By what absolute factor is the influence of yky_k multiplied from one interval to the next?

Summary

Key idea
Polynomial interpolation is stable and cheap with barycentric evaluation and Chebyshev nodes; Runge’s disaster comes from equally spaced nodes, whose Lebesgue constant grows like 2n2^n. When nodes are fixed, use piecewise methods: cubic splines for smoothness, PCHIP to preserve shape.
  • The degree-≤n\le n interpolant through n+1n + 1 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 O(n2)\bigO(n^2) (or O(n)\bigO(n) with closed forms), evaluation in O(n)\bigO(n); the first form is backward stable and the second forward stable for nodes with small Λn\Lambda_n.
  • Error: f(x)−p(x)=f(n+1)(ξ) ω(x)/(n+1)!f(x) - p(x) = f^{(n+1)}(\xi)\,\omega(x)/(n + 1)!. The node factor ω\omega is minimized by roots of TmT_m, equioscillating at height 21−m2^{1-m}.
  • Λn=max⁡∑j∣ℓj∣\Lambda_n = \max\sum_j\abs{\ell_j} is interpolation’s condition number and the factor in Lebesgue’s inequality: ∼2n+1/(e nlog⁡n)\sim 2^{n+1}/(e\,n\log n) with equally spaced nodes, ≤2πlog⁡(n+1)+1\le \tfrac{2}{\pi}\log(n + 1) + 1 with Chebyshev.
  • With Chebyshev, smoothness sets speed: O(n−ν)\bigO(n^{-\nu}) with ν\nu derivatives and O(ρ−n)\bigO(\rho^{-n}) for analytic functions.
  • Cubic splines: C2C^2, tridiagonal moment system, error O(h4)\bigO(h^4) for not-a-knot or clamped and O(h2)\bigO(h^2) near natural-spline boundaries. PCHIP: C1C^1, never overshoots data. Bilinear: weighted average of four corners with area weights.