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?