How to turn an array into a callable function

I have a function np.piecewise

that I would like to turn into a callable.

For example, suppose we have:

import numpy as np
x = np.linspace(0,10,1001)
my_func = np.piecewise(x, [x<8, x>=8], [np.sin, np.cos])

      

I'm interested in making a function my_callable_func

that has some reasonable evaluation of my_func. Reasonably, either we just default in the previous step in x

, or we use some kind of linear approximation between successive values x

.

For example, in this case x = [0, 0.01, 0.02, ...]

, so given my_new_func(0.015)

, I would like this to return np.sin(0.01)

or something ...

+3


source to share


1 answer


You can just wrap the call np.piecewise

inside the function definition,

In [1]: def my_callable_func(x):
   ...:     return np.piecewise(x, [x<8, x>=8], [np.sin, np.cos])
   ...: my_callable_func(0.015)

Out[1]: array(0.01499943750632809)

      



The value of your original vector x

doesn't matter. This creates a 0D numpy array, but you can float it with return float(...)

.

+3


source







All Articles