问题
Given a symbolic multivariate polynomial P, I need to extract both its coefficients and corresponding monomials as lists:
def poly_decomp(P):
....
return coeffs, monoms
such that P is the dot product of coefficients and monomials, e.g., if P(x,y) = ax**2 + bxy + cy**2 then we should get coeffs = [a, b, c] and monoms = [x**2, x*y, y**2].
Getting the coefficients is easy since the function is built in coeffs = P.coeffs(). However, I'm having trouble getting the monomials. Here the build in function returns a list of exponents, e.g., in the example above we would get P.monoms() = [(2,0),(1,1),(0,2)].
Obviously the idea would be, provided a list of the variables var=[x,y], to do something like
powers = P.monoms()
monoms = [sympy.prod(x**k for x,k in zip(var, mon)) for mon in powers ]
However the polynomial class doesn't seem to offer a function that returns a list of variables. All I could find were the methods free_symbols and free_symbols_in_domain which return the sets {a, b, c, x, y} and {a, b, c}. So by taking their difference one could get the set {x, y}.
However then we are faced with the issue that the sets are unordered, hence converting it into a list might mess up the order in different ways depending on the number of variables.
I am kind of at a loss here. Any tips?
回答1:
The property gens (short for generators) holds a tuple of variables in the polynomial.
from sympy import *
x, y = symbols('x y')
p = Poly(x**3 + 2*x**2 + 3*x*y + 4*y**2 + 5*y**3, x, y)
q = Poly(x**3 + 2*x**2 + 3*x*y + 4*y**2 + 5*y**3, y, x)
print(p.gens) # (x, y)
print(q.gens) # (y, x)
So,
[prod(x**k for x, k in zip(p.gens, mon)) for mon in p.monoms()]
returns [x**3, x**2, x*y, y**3, y**2].
来源:https://stackoverflow.com/questions/50563745/extract-coefficients-and-corresponding-monomials-from-a-given-polynomial-in-symp