Python Program for Linear Interpolation
To interpolate value of dependent variable y at some point of independent variable x using Linear Interpolation, we take two points i.e. if we need to interpolate y corresponding to x which lies between x0 and x1 then we take two points [x0, y0] and [x1, y1] and constructs Linear Interpolants which is the straight line between these points i.e.
y - y0 = ((y1 - y0)/(x1 - x0)) * (x - x0)
And if value of y is need to be obtained then using above equation we calculate yp at x = xp as:
yp = y0 + ((y1 - y0)/(x1 - x0)) * (xp - x0)
Similarly, if we need to interpolate y corresponding to x which lies between x1 and x2 then we take two points [x1, y1] and [x2, y2] and constructs Linear Interpolants which is the straight line between these points i.e.
y - y1 = ((y2 - y1)/(x2 - x1)) * (x - x1)
And if value of y is need to be obtained then using above equation we calculate yp at x = xp as:
yp = y1 + ((y2 - y1)/(x2 - x1)) * (xp - x1)
This python program implements Linear interpolation algorithm as discussed above to interpolate intermediate value.
Python Source Code: Linear Iterpolation
# Linear interpolation in python
# Input section
# Reading first point
print('Enter first point:')
x0 = float(input('x0 = '))
y0 = float(input('y0 = '))
# Reading second point
print('Enter second point:')
x1 = float(input('x1 = '))
y1 = float(input('y1 = '))
# Reading calculation point
xp = float(input('Enter calculation point xp: '))
# Calculating interpolated value
yp = y0 + ((y1-y0)/(x1-x0)) * (xp - x0)
# Displaying result
print('Interpolated value at %0.4f is %0.4f' %(xp,yp))
Output: Linear Interpolation Python
Consider we have interpolation problem stated as: "From some observation it is found that pressure recorded at temperature 35°C is 5.6KPa and at 40°C is 7.4 KPa. Later it is required to use pressure at 37°C which is not in observation table. So pressure value at 37°C need to be Interpolated and this can be calculated using above program as:"
Enter first point: x0 = 35 y0 = 5.6 Enter second point: x1 = 40 y1 = 7.4 Enter calculation point xp: 37 Interpolated value at 37.0000 is 6.3200