Linear Interpolation#
A plot of two lists of points, with an intermediate point being interpolated between two reference points#
Linear interpolation relies on knowing the values of two points, then a straight line equation can be drawn between them and the intermediate value estimated. The form of the underlying equation creating those points remains unknown.
This is the same as the form showing the slope (gradient) and intercept of the line with the x-axis.
Substituting for the two points \((x_0,y_0)\) and \((x_1,y_1)\)
This equation is similar to the Lerp function used to calculate colours between two known colours. Look carefully at equation (1.1) and note how the variables are arranged, a similar arrangement will be shown in the Lagrange interpolation. When plotting, no additional computation is made explicitly, a command is given to the program to join from point to point by lines. To render the lines intermediate points must be drawn and linear interpolation is used to calculate where these lie.
Our example shows an intermediate point being calculated.
Show/Hide Code linear_interp.py
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
def lin_interp(x0, y0, x1, y1, x):
return y0 + (x - x0)*(y1 - y0)/(x1 - x0)
x = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
y = [4, 7, 11, 16, 22, 29, 38, 49, 63, 80]
xi = 13
yi = lin_interp(x[5],y[5],x[6],y[6], xi)
#create plot of x vs. y
plt.plot(x, y, '-ob')
plt.plot(xi, yi, 'or')
plt.text(xi * (1 + 0.02), yi * (1 - 0.04), (xi, yi), c='r')
plt.text(x[5] * (1 + 0.02), y[5] * (1 - 0.05), (x[5], y[5]), c='b')
plt.text(x[6] * (1 + 0.02), y[6] * (1 - 0.03), (x[6], y[6]), c='b')
plt.xlabel(r'$x$')
plt.ylabel(r'$f(x)$')
plt.title('Linear Interpolation')
plt.show()
#plt.savefig('../../figures/lin_interp.png')
If the plot rapidly changes its slope linear interpolation is best replaced by one of the methods following.