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:
- A set of points where you want the interpolated value (
x
) - A set of points with a known value (
points
) - 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");
Easy enough.