Linear Interpolation in Python: An np.interp() Example

Ben Cook • Posted 2021-02-15 • Last updated 2021-10-21

Say we have a set of points generated by an unknown polynomial function, we can approximate the function using linear interpolation. To do this in Python, you can use the np.interp() function from NumPy:

import numpy as np

points = [-2, -1, 0, 1, 2]
values = [4, 1, 0, 1, 4]

x = np.linspace(-2, 2, num=10)
y = np.interp(x, points, values)

Notice that you have to pass in:

  1. A set of points where you want the interpolated value (x)
  2. A set of points with a known value (points)
  3. The set of known values (values)

Let’s plot the known points in blue and the interpolated points in orange so we can see what’s happening:

import matplotlib.pyplot as plt

plt.plot(points, values, 'o')
plt.plot(x, y, 'o', alpha=0.5)

numpy interpolate quadratic function

Easy enough.