Linear interpolation is the process of estimating an unknown value of a function between two known values.
Given two known values (x1, y1) and (x2, y2), we can estimate the y-value for some point x by using the following formula:
y = y1 + (x-x1)(y2-y1)/(x2-x1)
We can use the following basic syntax to perform linear interpolation in Python:
import scipy.interpolate y_interp = scipy.interpolate.interp1d(x, y) #find y-value associated with x-value of 13 print(y_interp(13))
The following example shows how to use this syntax in practice.
Example: Linear Interpolation in Python
Suppose we have the following two lists of values in Python:
x = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] y = [4, 7, 11, 16, 22, 29, 38, 49, 63, 80]
We can create a quick plot x vs. y:
import matplotlib.pyplot as plt
#create plot of x vs. y
plt.plot(x, y, '-ob')
Now suppose that we’d like to find the y-value associated with a new x-value of 13.
We can use the following code to do so:
import scipy.interpolate
y_interp = scipy.interpolate.interp1d(x, y)
#find y-value associated with x-value of 13
print(y_interp(13))
33.5
The estimated y-value turns out to be 33.5.
If we add the point (13, 33.5) to our plot, it appears to match the function quite well:
import matplotlib.pyplot as plt
#create plot of x vs. y
plt.plot(x, y, '-ob')
#add estimated y-value to plot
plt.plot(13, 33.5, 'ro')
We can use this exact formula to perform linear interpolation for any new x-value.
Additional Resources
The following tutorials explain how to fix other common errors in Python:
How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes