简体   繁体   中英

multiple functions as arguments in python

I have the following problem: I have two sets of data (set T and set F). And the following functions:

x(T) = arctan(T-c0), A(x(T)) =  arctan(x(T) -c1),    
B(x(T)) =  arctan(x(T) -c2) 
and Y(x(t),F) = ((A(x(t)) - B(x(t)))/2 - A(x(t))arctan(F-c3) +  B(x(t))arctan(F-c4))
# where c0,c1,c2,c3,c4 are constants 

Now I want to create a surface plot of Y . And for that I would like to implement Y as a python (numpy) function what turns out to be quite complicated, because Y takes other functions as input.

Another idea of mine was to evaluate x , B and A on the data separately and store the results in numpy arrays. With those I also could get the output of the function Y , but I don't know which way is better in order to plot the data and I really would like to know how to write Y as a python function.

Thank you very much for your help

It is absolutely possible to use functions as input parameters to other functions. A use case could look like:

def plus_one(standard_input_parameter_like_int):
    return standard_input_parameter_like_int + 1

def apply_function(function_as_input, standard_input_parameter):
    return function_as_input(standard_input_parameter)

if(__name__ == '__main__'):
    print(apply_function(plus_one, 1))

I hope that helps to solve your specific problem.

  1. [...] somethin like def s(x,y,z,*args,*args2): will yield an error.

This is perfectly normal as (at least as far as I know) there is only one variable length non-keyword argument list allowed per function (that has to be exactly labeled as *args). So if you remove the asterisks (*) you should actually be able to run s properly.

  1. Regarding your initial question you could do something like:

     c = [0.2,-0.2,0,0,0,0] def x(T): return np.arctan(Tc[0]) def A(xfunc,T): return np.arctan(xfunc(T) - c[1]) def B(xfunc,T): return np.arctan(xfunc(T) - c[2]) def Y(xfunc,Afunc,Bfunc,t,f): return (Afunc(xfunc,t) - Bfunc(xfunc,t))/2.0 - Afunc(xfunc,t) * np.arctan(f - c[3]) + Bfunc(xfunc,t)*np.arctan(fc[4]) _tSet = np.linspace(-1,1,20) _fSet = np.arange(-1,1,20) print Y(x,A,B,_tSet,_fSet) 

As you can see (and probably already tested by yourself judging from your comment) you can use functions as arguments. And as long as you don't use any 'if' conditions or other non-vectorized functions in your 'sub'-functions the top-level function should already be vectorized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM