How to do a symbolic taylor expansion of an unknown function $f(x)$ using sympy

后端 未结 2 1784
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 10:43

In sage it is fairly easy to do a Taylor expansion of an unknown function f(x),

x = var(\'x\')
h = var(\'h\')
f = function(\'f\',x)
g1 = taylor(f,x,h,2)         


        
2条回答
  •  生来不讨喜
    2021-02-20 11:09

    As @asmeurer described, this is now possible with

    from sympy import init_printing, symbols, Function
    init_printing()
    
    x, h = symbols("x,h")
    f = Function("f")
    
    pprint(f(x).series(x, x0=h, n=3))
    

    or

    from sympy import series
    pprint(series(f(x), x, x0=h, n=3))
    

    both returns

                                                  ⎛  2        ⎞│                          
                                                2 ⎜ d         ⎟│                          
                                        (-h + x) ⋅⎜────(f(ξ₁))⎟│                          
                                                  ⎜   2       ⎟│                          
                    ⎛ d        ⎞│                 ⎝dξ₁        ⎠│ξ₁=h    ⎛        3       ⎞
    f(h) + (-h + x)⋅⎜───(f(ξ₁))⎟│     + ──────────────────────────── + O⎝(-h + x) ; x → h⎠
                    ⎝dξ₁       ⎠│ξ₁=h                2                                    
    

    If you want a finite difference approximation, you can for example write

    FW = f(x+h).series(x+h, x0=x0, n=3)
    FW = FW.subs(x-x0,0)
    pprint(FW)
    

    to get the forward approximation, which returns

                                      ⎛  2        ⎞│
                                    2 ⎜ d         ⎟│
                                   h ⋅⎜────(f(ξ₁))⎟│
                                      ⎜   2       ⎟│
              ⎛ d        ⎞│           ⎝dξ₁        ⎠│ξ₁=x₀    ⎛ 3    2        2    3                 ⎞
    f(x₀) + h⋅⎜───(f(ξ₁))⎟│      + ────────────────────── + O⎝h  + h ⋅x + h⋅x  + x ; (h, x) → (0, 0)⎠
              ⎝dξ₁       ⎠│ξ₁=x₀             2
    

提交回复
热议问题