As I understand your question, you want to write some function y = interpolate(x_values, y_values, x), which will give you the y value at some x? The basic idea then follows these steps:
- Find the indices of the values in
x_valueswhich define an interval containingx. For instance, forx=3with your example lists, the containing interval would be[x1,x2]=[2.5,3.4], and the indices would bei1=1,i2=2 - Calculate the slope on this interval by
(y_values[i2]-y_values[i2]y_values[i1])/(x_values[i2]-x_values[i1])(iedy/dx). - The value at
xis now the value atx1plus the slope multiplied by the distance fromx1.
You will additionally need to decide what happens if x is outside the interval of x_values, either it's an error, or you could interpolate "backwards", assuming the slope is the same as the first/last interval.
Did this help, or did you need more specific advice?