I aim to write a multidimensional Taylor approximation using sympy
, which
def mtaylor(funexpr,x,mu,order=1):
nvars = len(x)
hlist = ['__h' + str(i+1) for i in range(nvars)]
command=''
command="symbols('"+' '.join(hlist) +"')"
hvar = eval(command)
#mtaylor is utaylor for specificly defined function
t = symbols('t')
#substitution
loc_funexpr = funexpr
for i in range(nvars):
locvar = x[i]
locsubs = mu[i]+t*hvar[i]
loc_funexpr = loc_funexpr.subs(locvar,locsubs)
#calculate taylorseries
g = 0
for i in range(order+1):
g+=loc_funexpr.diff(t,i).subs(t,0)*t**i/math.factorial(i)
#resubstitute
for i in range(nvars):
g = g.subs(hlist[i],x[i]-mu[i])
g = g.subs(t,1)
return g
x1,x2,x3,x4,x5 = symbols('x1 x2 x3 x4 x5')
funexpr=1+x1+x2+x1*x2+x1**3
funexpr=cos(funexpr)
x=[x1,x2,x3,x4,x5]
mu=[1,1,1,1,1]
mygee = mtaylor(funexpr,x,mu,order=4)
print(mygee)