Linear Interpolation

Prerequisites

Gradient of a straight line Show

Interpolation Show

Linear Interpolation

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:
    1. Find the two points that surround the point you are estimating: one will be smaller, one larger.
    2. Draw a straight line between the two known points.
    3. 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:
    X1234567
    y282196961208750
    Find the value for y when x is 2.4
  1. The points the surround 2.4 are (2, 21) and (3, 96)
  2. We calculate the gradient of this line:
  3. And then find the value of y when x is 2.4:
  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)) # prints 50.99999999999999
print(interpolator(2.6)) # prints 66.0

Code (using NumPy)

import numpy as np

class LinearInterpolator:
    # an array of x values, in order
    _sortedDomain = []

    # a dictionary of x, y values
    _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):
        # find the index of the smallest element larger than x
        closest = np.searchsorted(self._sortedDomain, x)

        # find the two x values (before and after x
        x1 = self._sortedDomain[closest - 1]
        x2 = self._sortedDomain[closest]

        # and their corresponding y values
        y1 = self._dataPointsDict[x1]
        y2 = self._dataPointsDict[x2]

        # find the deltaX and deltaY
        deltaX = x2 - x1
        deltaY = y2 - y1

        # calculate the gradient
        gradient = deltaY / deltaX

        # and finally interpolate
        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)) # 50.99999999999999
print(interpolator.interpolate(2.6)) # 66.0