【问题标题】:How to do a symbolic taylor expansion of an unknown function $f(x)$ using sympy如何使用 sympy 对未知函数 $f(x)$ 进行符号泰勒展开
【发布时间】:2016-04-01 17:14:29
【问题描述】:

sage 中,对未知函数进行泰勒展开是相当容易的f(x),

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

如何在 sympy 中做到这一点?


更新

asmeurer 指出,这是一个很快就会在拉取请求 http://github.com/sympy/sympy/pull/1888 中提供的功能。我使用 pip 安装了分支,

pip install -e git+git@github.com:renatocoutinho/sympy.git@897b#egg=sympy --upgrade

但是,当我尝试计算 f(x) 的系列时,

x, h = symbols("x,h")
f = Function("f")
series(f,x,x+h)

我收到以下错误,

TypeError: 未绑定的方法 series() 必须使用 f 实例调用 第一个参数(取而代之的是 Symbol 实例)

【问题讨论】:

  • 你不能。只需使用循环和diff。该函数称为series 而不是taylor
  • github.com/sympy/sympy/pull/1888 有一个拉取请求来完成这项工作。
  • @asmeurer 太棒了!这还没有合并到主分支中,是否仍然可以使用 pip 安装它。还是我需要克隆 repo,应用补丁,然后从源代码构建?
  • @asmeurer 我尝试使用 git apply 将github.com/sympy/sympy/pull/1888.patch 应用于 sympy 的最新主副本,但失败了。你有什么推荐的?
  • 最简单的方法是在他的分支上工作,直到合并该拉取请求。

标签: python sympy


【解决方案1】:

正如@asmeurer 所述,现在可以使用

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))

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

两个都返回

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

如果你想要一个有限差分近似,你可以例如写

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

得到前向近似,它返回

                                  ⎛  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

【讨论】:

    【解决方案2】:

    sympy 中没有这个功能,但是“手动”很容易做到:

    In [3]: from sympy import *
            x, h = symbols('x, h')
            f = Function('f')
            sum(h**i/factorial(i) * f(x).diff(x, i) for i in range(4))
    
    Out[3]: h**3*Derivative(f(x), x, x, x)/6 + h**2*Derivative(f(x), x, x)/2 + h*Derivative(f(x), x) + f(x)
    

    请注意,sympy 通常适用于表达式(如 f(x)),而不适用于裸函数(如 f)。

    【讨论】:

      猜你喜欢
      • 2017-04-02
      • 2020-01-05
      • 2021-07-10
      • 2021-02-08
      • 2017-06-29
      • 1970-01-01
      • 2014-06-11
      • 2017-06-14
      • 2022-06-18
      相关资源
      最近更新 更多