GBA13
GBA13

Reputation: 215

How does this interpolating function work?

I am trying to write a function which interpolates some data and then you can chose any value on the x axis to find the corresponding point on the y axis.

For example:

f = f_from_data([3, 4, 6], [0, 1, 2])
print f(3.5)

produces the answer

0.5

I came across an answer which looks like this:

def f_from_data(xs,ys):
    return scipy.interpolate.interp1d(xs, ys)

Can someone please explain how this works? I understand interp1d but I'm not sure how this simple line of code can get the answer when, for example

print f(5)

is input into it.

Upvotes: 0

Views: 2103

Answers (3)

Hooked
Hooked

Reputation: 88218

A simple example may help. interp1d is a class that acts like a function. It returns not a number, but another function-like object. Once you call it again, it returns the interpolated value of y at the input value of x. You can also feed this function single points, or whole arrays:

import numpy as np
from scipy.interpolate import interp1d

X=[3,4,6]
Y=[0,1,2]

f = interp1d(X,Y, bounds_error=False)
print f(3.5)

X2 = np.linspace(3, 6, 5)
print X2
print f(X2)

0.5
[ 3.    3.75  4.5   5.25  6.  ]
[ 0.     0.75   1.25   1.625  2.   ]

Upvotes: 3

Hugh Bothwell
Hugh Bothwell

Reputation: 56694

Your example uses linear interpolation - straight connecting lines between data points.

So, for your given data (xs = [3, 4, 6] and ys = [0, 1, 2]) the function looks like

chart of interpolated function

where the blue points are the input data, the green line is the interpolated function, and the red dot is the test point f(3.5) == 0.5


To calculate f(5.0):

First, you have to find out which line segment you are on.

x == 5 is in the second segment, between 4 and 6, so we are looking for point C (5, y) between points A (4, 1) and B (6, 2).

C is on the line, so AC = k * AB where 0. <= k < 1.; this gives us two equations in two unknowns (k and y). Solving, we get

y = Ay + (By - Ay) * (Cx - Ax) / (Bx - Ax)

and subbing in,

y = 1. + (2. - 1.) * (5. - 4.) / (6. - 4.)
  = 1.5

so the interpolated point is C (5, 1.5) and the function returns f(5.0) = 1.5


From the above, you should be able to write your own f() function given xs and ys; and this is exactly what scipy.interpolate.interp1d(xs, ys) does - takes xs and ys and returns an interpolative function, ie

f = scipy.interpolate.interp1d([3, 4, 6], [0, 1, 2])

# f is now a function that you can call, like
f(5.0)      # =>  1.5

Upvotes: 2

Simon
Simon

Reputation: 10841

To quote the documentation:

This class returns a function whose call method uses interpolation 
to find the value of new points.

Thus, calling the returned function with an x value gives the corresponding interpolated y value.

Upvotes: 1

Related Questions