How to get coefficients in sympy expression
b = sympy.Symbol('b')
a = sympy.Symbol('a')
x = sympy.Symbol('x')
y = 2*x**3 + a*x**2 +b*x
The result should be :
coeff for x**3 =2
coeff for x**2 = a
coeff for x = b
How to get coefficients in sympy expression
b = sympy.Symbol('b')
a = sympy.Symbol('a')
x = sympy.Symbol('x')
y = 2*x**3 + a*x**2 +b*x
The result should be :
coeff for x**3 =2
coeff for x**2 = a
coeff for x = b
It is surprisingly awkward to get the expression form of the terms in the polynomial but you can do it like this:
In [28]: b = sympy.Symbol('b')
...: a = sympy.Symbol('a')
...: x = sympy.Symbol('x')
...:
...: y = 2*x**3 + a*x**2 +b*x
In [29]: p = Poly(y, x)
In [30]: p
Out[30]: Poly(2*x**3 + a*x**2 + b*x, x, domain='ZZ[a,b]')
In [31]: {x**m[0]:p.coeff_monomial(m) for m in p.monoms()}
Out[31]:
⎧ 2 3 ⎫
⎨x: b, x : a, x : 2⎬
⎩ ⎭
Although getting the coefficients is easy
>>> y = 2*x**3 + a*x**2 + b
>>> p = Poly(y, x)
>>> p.coeffs()
[2, a, b]
>>> p.all_coeffs()
[2, a, 0, b]
getting them linked up to their monomial is the unimplemented/ackward part. @OscarBenjamin showed how to do this with the monomials of the Poly. You can also work with the expression without converting it to a Poly:
>>> dict(i.as_independent(x)[::-1] for i in Add.make_args(y))
{1: b, x**3: 2, x**2: a}
It would be a nice "battery" for SymPy to include a mapping
keyword on Poly.coeffs
that would allow this dictionary to be returned. Alternatively, Expr.as_coefficients_dict
could be given an optional variable
keyword that would allow the coefficients to be returned which are indepenedent of any symbols in variable
.
This simple dict-comprehension will fail if there are uncollected terms like a*x + b*x
in the expression. A more robust little function is posted here.