Polynomial interpolation

Part 6 — Interpolation and approximation

Numerical analysis for biologists

About this lecture

Measurements come at a few time points; questions are asked in between. This lecture is about drawing one polynomial through all the points, and about when that is a bad idea.

  • Through n+1 points there is exactly one polynomial of degree \le n. Three ways to write it: monomial (Vandermonde), Lagrange, Newton (divided differences).
  • The interpolation error has a formula: a derivative of the curve times the node polynomial \prod (t - t_i).
  • With equally spaced time points, a high degree makes things worse, not better: the Runge phenomenon. Chebyshev points fix it.
  • Interpolation reproduces noise exactly; with noisy data, fit instead (least squares).
  • Evaluate with the barycentric formula, not with monomial coefficients.

A biology problem first

  • A culture is read every 2 h (red). RNA was extracted at 3 h and 5 h, between readings. What was the OD then?
  • The truth is our logistic curve from Convergence and cost, N(t) = K/(1 + (K/N_0 - 1)e^{-rt}), K = 1.2, N_0 = 0.05, r = 0.8 per hour. In the lab you only have the dots.
  • The same question for a gene-expression time course: values at 0, 1, 2, 4, 8 h, and you want 3 h.

One polynomial through all the points

n+1 readings at distinct times t_0, \dots, t_n → exactly one polynomial p(t) = c_0 + c_1 t + \dots + c_n t^n with p(t_i) = y_i. Two points: a line; three: a parabola.

The conditions p(t_i) = y_i are a square linear system with the Vandermonde matrix:

K <- 1.2; N0 <- 0.05; r <- 0.8
od <- function(t) K / (1 + (K / N0 - 1) * exp(-r * t))
t <- c(0, 2, 4, 6, 8);  y <- od(t)          # 5 readings
V  <- outer(t, 0:4, "^")                    # columns 1, t, t^2, t^3, t^4
cf <- solve(V, y)                           # coefficients c0 ... c4
p  <- function(x) drop(outer(x, 0:4, "^") %*% cf)
p(c(3, 5));  od(c(3, 5))
# [1] 0.4026258 0.8312495                   # interpolant
# [1] 0.3887883 0.8443214                   # truth
  • Off by +0.014 and −0.013 OD, about 3 %. Not bad for a guess between readings.
  • This is the polynomial fit of Least squares: normal equations vs QR with as many coefficients as points: the residuals are zero.

Lagrange form

Build p from basis polynomials L_i(t) that are 1 at t_i and 0 at every other node:

L_i(t) = \prod_{j \ne i} \frac{t - t_j}{t_i - t_j}, \qquad p(t) = \sum_{i=0}^{n} y_i\, L_i(t).

No linear system to solve. By hand, nodes t = 2, 4, 6, evaluate at t = 3:

L_0(3) = \tfrac{(3-4)(3-6)}{(2-4)(2-6)} = \tfrac{3}{8}, \quad L_1(3) = \tfrac{(3-2)(3-6)}{(4-2)(4-6)} = \tfrac{3}{4}, \quad L_2(3) = \tfrac{(3-2)(3-4)}{(6-2)(6-4)} = -\tfrac{1}{8}

p(3) = \tfrac38(0.2126) + \tfrac34(0.6193) - \tfrac18(1.0090) = 0.4181 \qquad (\text{truth } 0.3888)

  • The weights L_i(3) add up to 1: interpolating a constant gives the constant back.
  • A negative weight (-\tfrac18): the value at 3 h is pulled down by the reading at 6 h.

The Lagrange basis

  • L_i is 1 at its own node and 0 at the others; in between it is free to swing.
  • Near the ends of the interval the swings are larger. Remember this picture for the Runge slides.

Lagrange in R

lagrange <- function(x, y, xx) {
  sapply(xx, function(z) {
    L <- sapply(seq_along(x), function(i) prod((z - x[-i]) / (x[i] - x[-i])))
    sum(L * y)
  })
}
lagrange(t, y, c(3, 5))
# [1] 0.4026258 0.8312495               # the same polynomial as solve(V, y)
  • x[-i] is R for “all elements except the i-th”.
  • Cost: each L_i(z) is a product of n factors, so O(n^2) per evaluation point. Adding a reading means starting over.
  • Same numbers as the Vandermonde route: one polynomial, different ways of writing it.

Newton form

Write p so that each new node adds one term:

p(t) = a_0 + a_1(t - t_0) + a_2(t - t_0)(t - t_1) + \dots + a_n(t - t_0)\cdots(t - t_{n-1}).

The coefficients are divided differences: f[t_i] = y_i and

f[t_i, \dots, t_{i+k}] = \frac{f[t_{i+1}, \dots, t_{i+k}] - f[t_i, \dots, t_{i+k-1}]}{t_{i+k} - t_i}, \qquad a_k = f[t_0, \dots, t_k].

  • f[t_0, t_1] = \dfrac{y_1 - y_0}{t_1 - t_0} is a slope; f[t_0, t_1, t_2] is a change of slope, about f''/2.
  • In general f[t_0, \dots, t_k] = f^{(k)}(\xi)/k! for some \xi between the nodes: a derivative estimate from data.

Divided differences by hand

Readings at t = 2, 4, 6, 8 (rounded to 4 digits):

t_i y_i 1st 2nd 3rd
2 0.2126
$ = $ 0.20335
4 0.6193 $ = $ −0.002125
0.19485 $ = $ −0.004706
6 1.0090 −0.0303625
0.07340
8 1.1558

p(3) = 0.2126 + 0.20335(1) - 0.002125(1)(-1) - 0.004706(1)(-1)(-3) = 0.4040 (truth 0.3888)

  • The first three terms are the quadratic through 2, 4, 6: 0.4181, as on the Lagrange slide.
  • The 4th reading added one term (-0.0141) and changed nothing else.

Newton in R

divdiff <- function(x, y) {           # returns f[x0], f[x0,x1], ..., f[x0..xn]
  n <- length(x); a <- y
  for (k in 2:n)
    for (i in n:k) a[i] <- (a[i] - a[i - 1]) / (x[i] - x[i - k + 1])
  a
}
newton_eval <- function(x, a, xx) {   # nested multiplication, like Horner
  n <- length(a); p <- a[n]
  for (k in (n - 1):1) p <- a[k] + (xx - x[k]) * p
  p
}
newton_eval(t, divdiff(t, y), c(3, 5))
# [1] 0.4026258 0.8312495
  • The table costs O(n^2) once; each evaluation is then O(n).
  • Same polynomial again, as it must be.

How large is the error?

If the true curve f has n+1 derivatives, then for every t there is a \xi between the nodes and t with

f(t) - p(t) = \underbrace{\frac{f^{(n+1)}(\xi)}{(n+1)!}}_{\text{the curve}} \; \underbrace{(t - t_0)(t - t_1)\cdots(t - t_n)}_{\text{node polynomial } w(t):\ \text{the sampling}}

  • One more derivative than the degree: a polynomial of degree \le n is reproduced exactly (f^{(n+1)} = 0).
  • w(t) is zero at the nodes and depends only on where you sampled. You control it; you do not control f.
  • Same shape as Taylor’s remainder (Convergence and cost): Taylor has all n+1 factors equal to (t - t_0).

The error formula with numbers

Linear interpolation between the readings at 2 h and 4 h, at t = 3:

f(3) - p(3) = \frac{f''(\xi)}{2}(3-2)(3-4) = -\frac{f''(\xi)}{2}, \quad f''(3) = 0.0592 \;\Rightarrow\; \approx -0.0296

Actual: p(3) = (0.2126 + 0.6193)/2 = 0.4160, truth 0.3888, error -0.0272. ✓

Degree 4 through t = 0, 2, 4, 6, 8, with \max |f^{(5)}| = 0.0983 on [0, 8]:

t w(t) bound \frac{0.0983}{120}\,\lvert w(t)\rvert actual \lvert f - p\rvert
3 (middle) 3\cdot1\cdot(-1)(-3)(-5) = -45 0.037 0.014
1 (near the end) 1\cdot(-1)(-3)(-5)(-7) = 105 0.086 (exercise)
  • The bound holds; it is pessimistic because it uses the largest derivative.
  • The same nodes are 2.3 times worse near the ends: |w| is larger there.

A longer run: 48 h, a reading every 4 h

  • 13 readings, so a degree-12 interpolant. It passes through every reading, and dips to OD = −0.15 at 0.9 h: a negative cell density.
  • It also wiggles in stationary phase near 44–48 h. In the middle it is fine.
  • This is the Runge phenomenon (Carl Runge, 1901).

Why the ends? The node polynomial

  • Equispaced (red): |w(t)| is about 300 times larger between the first two readings than in the middle.
  • The error is |f^{(13)}(\xi)|/13! \times |w(t)|: the same derivative factor, multiplied by a much larger w at the ends.
  • Chebyshev times (blue, ticks on top) are crowded towards the ends, and |w| is level across the whole run.

More readings make it worse

  • 0–8 h, equispaced (green): error falls with n, by a factor \approx 1.6 per extra reading, until rounding sets in near 10^{-8}.
  • 0–48 h, equispaced (red): error jumps between 0.03 and 0.6 OD and does not converge.
  • 0–48 h, Chebyshev (blue): falls steadily, 2\times10^{-5} at n = 40.

Chebyshev nodes

On [-1, 1]: x_k = \cos\!\left(\dfrac{(2k+1)\pi}{2n+2}\right), k = 0, \dots, n. On [a, b]: t_k = \tfrac{a+b}{2} - \tfrac{b-a}{2}\,x_k.

They are the projections of equally spaced points on a semicircle, so they crowd at the ends.

n <- 12; k <- 0:n
tc <- 24 - 24 * cos((2 * k + 1) * pi / (2 * n + 2))   # 13 times in [0, 48] h
round(tc, 2)
#  [1]  0.17  1.56  4.25  8.09 12.85 18.26 24.00 29.74 35.15 39.91 43.75 46.44
# [13] 47.83
  • They minimise \max |w(t)|: the smallest possible value is 2\left(\tfrac{b-a}{4}\right)^{n+1}.
  • For a smooth curve the error then falls geometrically with n.

Chebyshev times on the same run

  • Same 13 readings’ worth of effort, same degree 12. Largest error 0.039 OD instead of 0.25, no negative OD.
  • In practice you rarely choose the times freely. With the times you have, use low degree, locally: a line between neighbours (approx), or the cubic splines of the next lecture, Splines.
approx(t, y, xout = c(3, 5))$y        # piecewise linear, 0-8 h readings
# [1] 0.4159873 0.8141777             # errors 0.027, -0.030

Try it: Runge and Chebyshev

Interpolation vs fitting

  • Hourly readings over 12 h with plate-reader noise (sd 0.02 OD). The degree-12 interpolant goes through the noise and swings to 0.39 OD off near the ends.
  • A degree-5 least-squares fit (blue) ignores the noise: error 0.032. Without noise, the interpolant’s error was only 0.008.

Interpolation vs fitting in R

set.seed(1)
t12 <- 0:12                                  # hourly for 12 h
y12 <- od(t12) + rnorm(13, sd = 0.02)        # plate-reader noise
f_int <- lm(y12 ~ poly(t12, 12))             # 13 coefficients: interpolation
f_fit <- lm(y12 ~ poly(t12, 5))              # 6 coefficients: least squares
max(abs(resid(f_int)))
# [1] 0                                       # passes through every point
tt <- seq(0, 12, by = 0.01)
max(abs(predict(f_int, data.frame(t12 = tt)) - od(tt)))
# [1] 0.3937819
max(abs(predict(f_fit, data.frame(t12 = tt)) - od(tt)))
# [1] 0.03161686
  • poly() builds orthogonal columns (a QR of the Vandermonde matrix), so even degree 12 is well conditioned.
  • Zero residuals are a warning sign, not a success: the model has as many parameters as data.

Monomial coefficients lose digits

t48 <- seq(0, 48, by = 4)
solve(outer(t48, 0:12, "^"), od(t48))
# Error in solve.default(...) :
#   system is computationally singular: reciprocal condition number = 5.66168e-23
  • In hours, t^{12} reaches 48^{12} \approx 10^{20}: \kappa(V) \approx 8\times10^{20}. R refuses from n = 9; forced (tol = 0, or numpy, which never refuses) the values go wrong from n \approx 22 (orange).
  • Rescaled to [-1, 1] (red) it lasts longer but stalls near 10^{-5}. Barycentric (blue) reaches 10^{-12}.

The barycentric form: the stable way to evaluate

Divide the Lagrange form by the Lagrange form of the constant 1:

p(t) = \frac{\displaystyle\sum_j \frac{w_j\, y_j}{t - t_j}}{\displaystyle\sum_j \frac{w_j}{t - t_j}}, \qquad w_j = \frac{1}{\prod_{k \ne j}(t_j - t_k)} \quad \left(\text{Chebyshev: } w_j = (-1)^j \sin\tfrac{(2j+1)\pi}{2n+2}\right)

bary_weights <- function(x) sapply(seq_along(x), function(j) 1 / prod(x[j] - x[-j]))
bary_eval <- function(x, y, w, xx) sapply(xx, function(z) {
  d <- z - x
  if (any(d == 0)) return(y[d == 0])          # z is a node
  sum(w * y / d) / sum(w / d)
})
bary_eval(t, y, bary_weights(t), c(3, 5))
# [1] 0.4026258 0.8312495
  • Weights O(n^2) once, then O(n) per point; a new reading updates the weights in O(n).
  • Rounding errors in numerator and denominator largely cancel: accurate to \approx\varepsilon times the Lebesgue constant. Python: scipy.interpolate.BarycentricInterpolator.

Checklist: is my interpolant trustworthy?

  1. Plot it on a fine grid, not only at the readings. Values outside the biology (negative OD, OD above the plateau) → Runge or noise.
  2. Leave one reading out, interpolate from the rest, compare at the left-out time: the difference estimates the error.
  3. Change the degree (drop the end readings, or add one): if the answer between readings changes a lot, do not trust it.
  4. Noisy readings? Do not interpolate: fit (least squares, lower degree) or smooth (Splines).
  5. Never extrapolate a polynomial beyond the first or last reading: |w(t)| grows like |t|^{n+1} outside.
  6. Evaluate stably: barycentric formula or poly(); not solve() on raw powers.

Summary

  • n+1 readings → one interpolating polynomial of degree \le n. Monomial (Vandermonde), Lagrange (\sum y_i L_i) and Newton (divided differences) are three ways to write the same polynomial.
  • Error: f(t) - p(t) = \dfrac{f^{(n+1)}(\xi)}{(n+1)!}\prod (t - t_i): a property of the curve times a property of the sampling.
  • Equispaced readings: |w| explodes near the ends, so a high degree diverges (Runge): a 48-h run read every 4 h gives a negative OD.
  • Chebyshev times (crowded at the ends) keep |w| level; the error then falls geometrically.
  • Readings are noisy: interpolation copies the noise and amplifies it; fit with fewer parameters instead.
  • Evaluate with the barycentric formula; raw powers of t are badly conditioned.

Next: Splines: low-degree pieces joined smoothly, the practical answer for real sampling times.