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 the interpolant is the straight line through the two data points:
Evaluating at requires finding the interval, a binary search in (np.searchsorted).
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: , where the hat function is the piecewise linear function that equals 1 at 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 the linear interpolation error is at most . With equal intervals on , and
second-order convergence. Doubling the number of points divides the error by 4.
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 = errn = 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:
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, 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, sortedxp),scipy.interpolate.interp1d(legacy) andmake_interp_spline(k=1);RegularGridInterpolatorandLinearNDInterpolatorfor 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 and at .
Answer
.
Solution
Slope ; .
Exercise 2: Points needed
How many equal intervals on guarantee error below for ?
Answer
.
Solution
gives .
Exercise 3: Hat functions (code)
Build the hat function for nodes by interpolating the data , and verify that equals np.interp for random (seed 91).
Answer
The two agree to rounding error (difference about ).
Solution
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 is…
- independent of
What is a hat function?
- A Gaussian
- A piecewise linear function equal to 1 at one node and 0 at the others
- A cubic spline
- A Chebyshev polynomial
Does piecewise linear interpolation suffer from Runge's phenomenon?
- Yes, badly
- No; it converges for any continuous function as
- Only with Chebyshev points
- Only for polynomials