I am currently writing a python definition called f_from_data which uses interpolation find point on a line so far I have written 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 is giving me what I want to I need to make it so I can enter:
f = f_from_data([3, 4, 6], [0, 1, 2])
print f(3)
>>>0.0
How do I go about doing this? I've looked around but can't seem to find anything as I think its really trivial but I'm just missing somthing.
How to Make an Object Callable. Simply, you make an object callable by overriding the special method __call__() . __call__(self, arg1, .., argn, *args, **kwargs) : This method is like any other normal method in Python. It also can accept positional and arbitrary arguments.
Definition and Usage The callable() function returns True if the specified object is callable, otherwise it returns False.
The “int object is not callable” error occurs when you declare a variable and name it with a built-in function name such as int() , sum() , max() , and others. The error also occurs when you don't specify an arithmetic operator while performing a mathematical operation.
Using functools.partial
:
from functools import partial
f = partial(f_from_data, [3, 4, 6], [0, 1, 2])
partial
will create a callable object with the first 2 arguments already set.
interpolate.interp1d returns a callable:
import scipy.interpolate as interpolate
f_from_data = interpolate.interp1d
f = f_from_data([3, 4, 6], [0, 1, 2])
print(f(3))
yields
0.0
Since f_from_data
can be assigned to interpolate.interp1d
, you may not need f_from_data
at all. Now, it is true that this does not chop the x-range into 10000 grid points, and use searchsorted to snap the x value to a nearby grid point, but in general you wouldn't want to do that anyway since interp1d
gives you a better linear interpolation without it.
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
Warning - I don't know matplotlib well enough to say whether the code is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With