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

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)

plt.xlabel("x")
plt.ylabel("y");
numpy interpolate quadratic function

Easy enough.

Hello, my name is Ben Cook

I help data scientists deploy their code. If there's any way I can serve you, don't hestitate to reach out. You can also find out a little more about me or download my free guide: 8 Best Practices for Building Machine Learning Pipelines.

Thanks for stopping by!

Contact

Get in touch

Connect

Free Guide

Download my free guide: 8 Best Practices for Building Machine Learning Pipelines