TExcelTAD
Home › Numerical Methods › Piecewise Linear Interpolation

Piecewise Linear Interpolation

Instead of one high-degree polynomial through all the data, use a simple low-degree piece between each pair of neighbouring points. Piecewise linear interpolation, "connect the dots", is what np.interp and every line chart do. It never oscillates, its cost is tiny, and its error is easy to bound.

The interpolant

On each interval [tk,tk+1][t_k, t_{k+1}] the interpolant is the straight line through the two data points:

p(x)=yk+yk+1−yktk+1−tk(x−tk),tk≤x≤tk+1.p(x) = y_k + \frac{y_{k+1} - y_k}{t_{k+1} - t_k}(x - t_k), \qquad t_k \le x \le t_{k+1}.

Evaluating at xx requires finding the interval, a binary search in O(log⁡n)O(\log n) (np.searchsorted).

python · try it yourself
import numpy as np

t = np.array([0.0, 1.0, 2.5, 4.0, 5.0])
y = np.array([1.0, 3.0, 2.0, 4.0, 0.0])

def pwlin(t, y, x):
    k = np.clip(np.searchsorted(t, x) - 1, 0, len(t) - 2)       # interval index
    slope = (y[k + 1] - y[k]) / (t[k + 1] - t[k])
    return y[k] + slope * (x - t[k])

x = np.array([0.5, 2.0, 3.0, 4.5])
print("ours     :", pwlin(t, y, x))
print("np.interp:", np.interp(x, t, y))
ours     : [2.         2.33333333 2.66666667 2.        ]
np.interp: [2.         2.33333333 2.66666667 2.        ]

Hat functions

The interpolant can also be written in a basis: p(x)=∑kykHk(x)p(x) = \sum_k y_k H_k(x), where the hat function HkH_k is the piecewise linear function that equals 1 at tkt_k and 0 at all other nodes. Hat functions are local (nonzero on two intervals only), which is why changing one data point changes the interpolant only nearby. They are also the basis functions of the simplest finite element method.

Error and convergence

On an interval of width hh the linear interpolation error is at most h28max⁡∣f′′∣\frac{h^2}{8}\max\lvert f''\rvert. With nn equal intervals on [a,b][a, b], h=b−anh = \frac{b - a}{n} and

∥f−p∥∞≤(b−a)28n2max⁡∣f′′∣=O(h2):\lVert f - p\rVert_\infty \le \frac{(b - a)^2}{8n^2}\max\lvert f''\rvert = O(h^2):

second-order convergence. Doubling the number of points divides the error by 4.

python · try it yourself
import numpy as np

f = lambda x: np.sin(3 * x) + 0.5 * x
xx = np.linspace(0, 2, 20001)
prev = None
for n in (10, 20, 40, 80, 160):
    t = np.linspace(0, 2, n + 1)
    err = np.max(np.abs(np.interp(xx, t, f(t)) - f(xx)))
    bound = (2 / n) ** 2 / 8 * 9                       # max |f''| = 9
    ratio = "" if prev is None else f", ratio {prev / err:.2f}"
    print(f"n = {n:3d}: error {err:.3e}, bound {bound:.3e}{ratio}")
    prev = err
n =  10: error 4.455e-02, bound 4.500e-02
n =  20: error 1.121e-02, bound 1.125e-02, ratio 3.98
n =  40: error 2.811e-03, bound 2.813e-03, ratio 3.99
n =  80: error 7.028e-04, bound 7.031e-04, ratio 4.00
n = 160: error 1.758e-04, bound 1.758e-04, ratio 4.00

Runge's function, which defeated equispaced polynomial interpolation, is no problem:

python · try it yourself
import numpy as np

f = lambda x: 1 / (1 + 25 * x**2)
xx = np.linspace(-1, 1, 4001)
for n in (10, 40, 160):
    t = np.linspace(-1, 1, n + 1)
    print(f"n = {n:3d}: max error {np.max(np.abs(np.interp(xx, t, f(t)) - f(xx))):.2e}")
n =  10: max error 6.74e-02
n =  40: max error 1.40e-02
n = 160: max error 9.69e-04

Trade-offs

  • Pro: robust, local, monotone data gives a monotone interpolant, no overshoot, O(h2)O(h^2) accuracy.
  • Con: the derivative jumps at the nodes (corners), and second-order convergence needs many points for high accuracy. Smooth curves need splines (Cubic Splines).

In software

  • np.interp(x, xp, fp) (1D, sorted xp), scipy.interpolate.interp1d (legacy) and make_interp_spline(k=1); RegularGridInterpolator and LinearNDInterpolator for 2D and higher.
  • Excel charts, game animation curves between keyframes and lookup tables in embedded firmware all use linear interpolation.

Exercises

Exercise 1: By hand

Interpolate linearly between (2,10)(2, 10) and (5,4)(5, 4) at x=3x = 3.

Answer

88.

Solution

Slope 4−103=−2\frac{4 - 10}{3} = -2; 10−2(3−2)=810 - 2(3 - 2) = 8.

Exercise 2: Points needed

How many equal intervals on [0,1][0, 1] guarantee error below 10−610^{-6} for f(x)=exf(x) = e^x?

Answer

n=583n = 583.

Solution

18n2e≤10−6\frac{1}{8n^2}e \le 10^{-6} gives n≥e⋅1068≈582.9n \ge \sqrt{\frac{e \cdot 10^6}{8}} \approx 582.9.

Exercise 3: Hat functions (code)

Build the hat function H2H_2 for nodes 0,1,2,3,40, 1, 2, 3, 4 by interpolating the data (0,0,1,0,0)(0, 0, 1, 0, 0), and verify that ∑kykHk\sum_k y_kH_k equals np.interp for random yy (seed 91).

Answer

The two agree to rounding error (difference about 2×10−162 \times 10^{-16}).

Solution
python · try it yourself
import numpy as np
t = np.arange(5.0); xx = np.linspace(0, 4, 101)
H = [np.interp(xx, t, np.eye(5)[k]) for k in range(5)]
y = np.random.default_rng(91).normal(size=5)
print(np.max(np.abs(sum(y[k] * H[k] for k in range(5)) - np.interp(xx, t, y))))
2.220446049250313e-16

Test yourself

The error of piecewise linear interpolation with spacing hh is…

  1. O(h)O(h)
  2. O(h2)O(h^2)
  3. O(h4)O(h^4)
  4. independent of hh

What is a hat function?

  1. A Gaussian
  2. A piecewise linear function equal to 1 at one node and 0 at the others
  3. A cubic spline
  4. A Chebyshev polynomial

Does piecewise linear interpolation suffer from Runge's phenomenon?

  1. Yes, badly
  2. No; it converges for any continuous function as h→0h \to 0
  3. Only with Chebyshev points
  4. Only for polynomials