简体   繁体   中英

Make sympy write out an expression in polynomial form

Currently, I have an expression of the form

(a+x^2) / b + x /c + xd + k

How can I make sympy to write it out in a polynomial form for x as

x^2 (.)+ x() + (.) 

And then I want to be able to access the coefficients of that polynomial, ie the terms in the brackets.

You can use the Poly class and the all_coeffs method. The reference is accessible here: https://docs.sympy.org/latest/modules/polys/reference.html

This is what it would give with your example, assuming all symbols have been declared:

>>> pol = sp.Poly(((a+x**2) / b + x /c + x*d + k), x); pol
Poly(1/b*x**2 + (c*d + 1)/c*x + (a + b*k)/b, x, domain='ZZ(a,b,c,d,k)')
>>> pol.all_coeffs()
[1/b, (c*d + 1)/c, (a + b*k)/b]

After that you can access each coefficient with its position.

If you expand the expression and collect on x you can then request the desired coefficients:

>>> eq = d*x + k + x/c + (a + x**2)/b
>>> ex = collect(eq.expand(), x); ex
a/b + k + x*(d + 1/c) + x**2/b
>>> ex.coeff(x**2)
1/b
>>> ex.coeff(x)
d + 1/c
>>> ex.subs(x, 0)  # the constant
a/b + k

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM