from sympy import Symbol
x = Symbol('x')
equation = x**2 2**x - 2*x - 5**x 1
Here, in this equation, for example, the polynomial part is x**2 - 2*x 1
while the non-polynomial part is 2**x - 5**x
.
Given an equation, how to extract the polynomial and the non-polynomial parts of it?
CodePudding user response:
Separate all the terms first,
lst = equation.args
Use the degree()
function in sympy module to find the degree of each term in lst
. It gives a PolynomialError
, if a term is not a polynomial.
Error can be handled using try ... except
statements.
CodePudding user response:
You can use the as_poly
method to find the terms that are polynomial in the given symbol:
In [1]: from sympy import Symbol
...:
...: x = Symbol('x')
...: equation = x**2 2**x - 2*x - 5**x 1
In [2]: poly, nonpoly = [], []
In [3]: for term in Add.make_args(equation):
...: if term.as_poly(x) is not None:
...: poly.append(term)
...: else:
...: nonpoly.append(term)
...:
In [4]: poly
Out[4]:
⎡ 2 ⎤
⎣1, x , -2⋅x⎦
In [5]: nonpoly
Out[5]:
⎡ x x⎤
⎣2 , -5 ⎦
In [6]: Add(*poly)
Out[6]:
2
x - 2⋅x 1
In [7]: Add(*nonpoly)
Out[7]:
x x
2 - 5
https://docs.sympy.org/latest/modules/core.html#sympy.core.expr.Expr.as_poly