By José Lopes
Though the Python math library has the linear interpolation that, if I'm not mistaken,
requires the adjacent points to the point we need the interpolation, I created my own function to do it.
I did it because I needed to do many interactions where the adjacent points changed, and also because
I failed to check first if Python had the linear interpolation function!
With this post I share my solution to anyone interested. It may come in handy if you are calculation several points with a bunch of initial data. Have a look!
The linear interpolation is an approximation method to calculate a point between two known points, assuming that a straight line between these points contains the point we want, has you may see with this image:
Knowing X we can calculate Y with:
y = y0 + (x - x0) (y1 - y0)/ (x1 - x0)
Now if we have a set of points (x0, y0), (x1, y1), ... (xn, yn) and we want to calculate the y coordinate for any given x value, then we can use the function that follows.
Let me first point out that for this example:
(1)def Linterpolation (xpoints, ypoints, value):
(2) for n in range(len(xpoints)):
(3) if (n==0 and value < xpoints[n]) or (n==len(xpoints)-1 and value > xpoints[n]):
(4) result = "Point outside the known values"
(5) elif value <= xpoints[n]:
(6) result = ypoints[n-1] + ((value-xpoints[n-1])*(ypoints[n]-ypoints[n-1]))/(xpoints[n]-xpoints[n-1])
return result
Let me explain the code:
(1) Declares the function taking as args the x and y coordinates lists and the x value that
we want the y coordinate calculated.
(2) To run through the list of known points.
(3) e (4) Tests to see if given coordinate is within the known values and return the
error message if not within.
(5) e (6) Checks if it finds the immediate upper adjacent value and runs the interpolation
once it finds.
This solved my problem on the moment but we can always find a more elegant solution or adapt
to our needs.
In this example I assumed that the known points were described by a list for each coordinate. I could
have used as arg a list of tuples like [(x0, y0),
(x1, y1), ...
(xn, yn)]
that is closer to the mathematic language.
Unfortunately my data usually doesn't come with this format and that is why it was more simple just to use two tables (lists).