Sympy中的多元泰勒近似 [英] Multivariate Taylor approximation in sympy
问题描述
我旨在使用sympy
编写多维泰勒逼近,其中
I aim to write a multidimensional Taylor approximation using sympy
, which
- 使用尽可能多的内置代码,
- 计算两个变量的给定函数的截断泰勒逼近
- 不使用大零余项返回结果 ,例如在
sin(x)=x - x**3/6 + O(x**4)
中.
- uses as many builtin code as possible,
- computes the truncated Taylor approximation of a given function of two variables
- returns the result without the Big-O-remainder term, as e.g. in
sin(x)=x - x**3/6 + O(x**4)
.
这是我到目前为止尝试过的:
Here is what I tryed so far:
方法1
天真的,对于每个变量,只需将series
命令组合两次,不幸的是,该命令不起作用,如本例所示的功能sin(x*cos(y))
:
Naively, one could just combine the series
command twice for each variable, which unfortunately does not work, as this example shows for the function sin(x*cos(y))
:
sp.sin(x*sp.cos(y)).series(x,x0=0,n=3).series(y,x0=0,n=3)
>>> NotImplementedError: not sure of order of O(y**3) + O(x**3)
方法2
基于这篇文章,我首先写了一维泰勒近似值:
Based on this post I first wrote a 1D taylor approximation:
def taylor_approximation(expr, x, max_order):
taylor_series = expr.series(x=x, n=None)
return sum([next(taylor_series) for i in range(max_order)])
使用一维示例进行检查很好
Checking it with 1D examples works fine
mport sympy as sp
x=sp.Symbol('x')
y=sp.Symbol('y')
taylor_approximation(sp.sin(x*sp.cos(y)),x,3)
>>> x**5*cos(y)**5/120 - x**3*cos(y)**3/6 + x*cos(y)
但是,如果我知道要同时在x
和y
中进行两个扩展,则链式调用会挂起
However, if I know do a chained call for doing both expansions in x
and y
, sympy hangs up
# this does not work
taylor_approximation(taylor_approximation(sp.sin(x*sp.cos(y)),x,3),y,3)
有人知道如何解决此问题或以其他方式实现它吗?
Does somebody know how to fix this or achieve it in an alternative way?
推荐答案
您可以使用expr.removeO()
从表达式中删除大O.
You can use expr.removeO()
to remove the big O from an expression.
Oneliner:expr.series(x, 0, 3).removeO().series(y, 0, 3).removeO()
Oneliner: expr.series(x, 0, 3).removeO().series(y, 0, 3).removeO()
这篇关于Sympy中的多元泰勒近似的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!