How to create a Callable function

I am currently writing a python definition called f_from_data that uses the interpolation search point on the string so far, I wrote this:

def f_from_data(xs, ys, x): xfine = np.linspace(min(xs), max(xs), 10000) y0 = inter.interp1d(xs, ys, kind = 'linear') ans = (y0(xfine))[numpy.searchsorted(xfine, x)] ans = round(ans,2) return ans 

This gives me what I want to do this so that I can enter:

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

How can I do it? I looked around, but could not find anything, because I think it is really trivial, but I'm just missing something.

+7
python numpy callable
source share
5 answers

Using functools.partial :

 from functools import partial f = partial(f_from_data, [3, 4, 6], [0, 1, 2]) 

partial will create the called object with 2 arguments already set.

+12
source share

interpolate.interp1d returns the called:

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

gives

 0.0 

Since f_from_data can be assigned interpolate.interp1d , you may not need f_from_data at all. Now it’s true that it does not interrupt the x-range of 10,000 grid points and uses searchsorted to bind the x value to an adjacent grid point, but in general you would not want to do this, since interp1d gives you the best linear interpolation without it.

+3
source share

Perhaps something like this?

 def f_from_data(xs, ys): def interpolate(x): xfine = np.linspace(min(xs), max(xs), 10000) y0 = inter.interp1d(xs, ys, kind = 'linear') ans = (y0(xfine))[numpy.searchsorted(xfine, x)] ans = round(ans,2) return ans return interpolate 

A warning. I do not know that matplotlib is good enough to say if the code is correct.

+2
source share

If you want simple, here is a simple solution

 >>> f = lambda x: f_from_data([3, 4, 6], [0, 1, 2], x) >>> print f(3) 0.0 >>> 

If you do not like lambda

 >>> def f(x): return f_from_data([3, 4, 6], [0, 1, 2], x) 

In both cases, you must be sure that f_from_data is in scope when defining a helper function.

+2
source share

A more general approach is to create a class using the __call__ method, so something like this:

 class f_from_data(object): def __init__(self, xs, ys): self.xfine = np.linspace(min(xs), max(xs), 10000) self.y0 = inter.interp1d(xs, ys, kind = 'linear') def __call__(self, x): ans = (self.y0(self.xfine))[numpy.searchsorted(self.xfine, x)] return round(ans, 2) 
+1
source share

All Articles