Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce a "Callable function"

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.

like image 811
GBA13 Avatar asked Dec 21 '14 18:12

GBA13


People also ask

How do you make a function callable?

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.

What is the use of callable () function?

Definition and Usage The callable() function returns True if the specified object is callable, otherwise it returns False.

Why is my function not callable?

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.


3 Answers

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.

like image 103
tmr232 Avatar answered Oct 24 '22 19:10

tmr232


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.

like image 27
unutbu Avatar answered Oct 24 '22 18:10

unutbu


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.

like image 34
Noufal Ibrahim Avatar answered Oct 24 '22 17:10

Noufal Ibrahim