Using Sympy, say we have an expression f, which is a polynomial of the Symbol "x" (and of potentially other symbols).
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.
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?
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.
An easy way to do this is to add
O(x**n)to the expression, likeIf you want to later remove it, use the
removeOmethodYou can also use
seriesto take the series expansion of the expression. The difference here is the behavior if a non-polynomial term ends up in the expression: