Multivariate Taylor approximation in sympy

后端 未结 3 1321
借酒劲吻你
借酒劲吻你 2021-01-05 08:18

I aim to write a multidimensional Taylor approximation using sympy, which

  • uses as many builtin code as possible,
  • computes the truncated T
3条回答
  •  走了就别回头了
    2021-01-05 09:02

    multivariate taylor expansion

    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
    

    test for some function

    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)
    

提交回复
热议问题