Sympy:删除多项式中的高阶项 [英] Sympy: Drop higher order terms in polynomial
问题描述
使用Sympy,假设我们有一个表达式f,它是符号"x"(以及其他可能的符号)的多项式.
Using Sympy, say we have an expression f, which is a polynomial of the Symbol "x" (and of potentially other symbols).
我想知道是否存在一种有效的方法来删除所有大于f的整数n的f中的所有项.
I would like to know what if there is an efficient way to drop all terms in f of order greater than some integer n.
作为一个特例,我有一个非常复杂的函数,但我只想将x的术语保持在2阶以内.有效的方法是什么?
As a special case I have a very complicated function but i want to only keep terms up to 2nd order in x. What's the efficient way to do this?
一个明显的,不是很有效的方法是对于每个小于n的m,取m个导数并将x设置为0,以获得x ^ m的系数.我们以这种方式获得每个系数,然后重构多项式.但是采用衍生工具并不是最有效的方法.
The obvious, not-very-efficient way to do it would be for each m less than n, take m derivatives and set x to 0 to obtain the coefficient of x^m. We obtain each coefficient this way then reconstruct the polynomial. But taking derivatives is not the most efficient thing.
推荐答案
一种简单的方法是将O(x**n)
添加到表达式中,例如
An easy way to do this is to add O(x**n)
to the expression, like
In [23]: x + x**2 + x**4 + x**10 + O(x**3)
Out[23]:
2 ⎛ 3⎞
x + x + O⎝x ⎠
如果以后要删除它,请使用removeO
方法
If you want to later remove it, use the removeO
method
In [24]: (x + x**2 + x**4 + x**10 + O(x**3)).removeO()
Out[24]:
2
x + x
您还可以使用series
进行表达式的系列扩展.此处的区别在于,如果非多项式项以表达式结尾:
You can also use series
to take the series expansion of the expression. The difference here is the behavior if a non-polynomial term ends up in the expression:
In [25]: x + sin(x) + O(x**3)
Out[25]:
⎛ 3⎞
sin(x) + x + O⎝x ⎠
In [26]: (x + sin(x)).series(x, 0, 3)
Out[26]:
⎛ 3⎞
2⋅x + O⎝x ⎠
这篇关于Sympy:删除多项式中的高阶项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!