python - How to make a Sympy lambdify(ed) function accept array input? -
i’m trying create function in python 2.7 accepts function handle , number of variables in function input , returns new function calculates gradient of input function. have far.
import sympy sym import numpy np def getsymbolicgradient(func,numvars): # initialize variables g = numvars * [0] # create symbolic variables x = sym.symarray('x',numvars) # calculate gradients in range(numvars): g[i] = sym.diff(func(x),x[i]) gradfunc = sym.lambdify(x, g, modules="numpy") return gradfunc
say use gradfunc
following code:
def myvecfunc(x): return 2*x[0]**2 + 4*x[1] + 2 gradfunc = getsymbolicgradient(func=myvecfunc, numvars=2)
if call using 2 separate arguments works, such following:
print( gradfunc(1,2) )
however, if call using single argument (say numpy array),
print( gradfunc(np.array([1,2])) )
i following error:
typeerror: () takes 2 arguments (1 given)
how can lambdify
accept input arguments single array inside of individual values? there better (built-in) sympy methods generating symbolic expression gradient of function accepts arrays inputs?
i'm not familiar numpy, in python can use *
operator unpack array values.
a = [2, 4, 6] my_func(*a)
is logically equivalent to
a = 2 b = 4 c = 6 my_func(a, b, c)
Comments
Post a Comment