Introduction
- Linear interpolation is a very simple type of interpolation.
- To find the value of a point which is not in the given set of points:
- Find the two points that surround the point you are estimating: one will be smaller, one larger.
- Draw a straight line between the two known points.
- Find the value of y for the point that lies on the line at the given x.
Visualization

Example
- If we are given a set of data points:Find the value for y when x is 2.4
- The points the surround 2.4 are (2, 21) and (3, 96)
- We calculate the gradient of this line:

- And then find the value of y when x is 2.4:

- When x is 2.4, y is 51
Code (using SciPy)
from scipy import interpolate
dataPoints = [
[1, 28],
[2, 21],
[3, 96],
[4, 96],
[5, 120],
[6, 87],
[7, 50]
]
interpolator = interpolate.interp1d(
[dataPoint[0] for dataPoint in dataPoints],
[dataPoint[1] for dataPoint in dataPoints],
'linear')
print(interpolator(2.4))
print(interpolator(2.6))
Code (using NumPy)
import numpy as np
class LinearInterpolator:
_sortedDomain = []
_dataPointsDict = {}
def __init__(self, dataPoints):
for dataPoint in dataPoints:
self._dataPointsDict[dataPoint[0]] = dataPoint[1]
self._sortedDomain = [dataPoint[0] for dataPoint in dataPoints]
self._sortedDomain = np.sort(self._sortedDomain)
def interpolate(self, x):
closest = np.searchsorted(self._sortedDomain, x)
x1 = self._sortedDomain[closest - 1]
x2 = self._sortedDomain[closest]
y1 = self._dataPointsDict[x1]
y2 = self._dataPointsDict[x2]
deltaX = x2 - x1
deltaY = y2 - y1
gradient = deltaY / deltaX
xPart = x - x1
yPart = xPart * gradient
return y1 + yPart
dataPoints = [
[1, 28],
[2, 21],
[3, 96],
[4, 96],
[5, 120],
[6, 87],
[7, 50]
]
interpolator = LinearInterpolator(dataPoints)
print(interpolator.interpolate(2.4))
print(interpolator.interpolate(2.6))