Skip to content Skip to sidebar Skip to footer

Extract Coefficients And Corresponding Monomials From A Given Polynomial In Sympy

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 su

Solution 1:

The property gens (short for generators) holds a tuple of symbols or other suitable objects that the polynomial is defined over.

from sympy import symbols, Poly

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 forx, k inzip(p.gens, mon)) formonin p.monoms()]

returns [x**3, x**2, x*y, y**3, y**2].

Note also that the generators can be types other than symbols, for example:

import sympy

x = sympy.symbols('x')
poly = sympy.poly(sympy.sqrt(2) * x**2)
print('generators: {g}'.format(g=poly.gens))
print('monomials: {m}'.format(m=poly.monoms()))
print('coefficients: {c}'.format(c=poly.coeffs()))

which prints:

generators: (x, sqrt(2))monomials: [(2, 1)]coefficients: [1]

where:

  • type(poly.gens[0]) is <class 'sympy.core.symbol.Symbol'>, and
  • type(poly.gens[1]) is <class 'sympy.core.power.Pow'>.

A relevant method is sympy.polys.polytools.Poly.as_dict, which returns a dict with keys that are monomials, and values that are the corresponding coefficients.

Post a Comment for "Extract Coefficients And Corresponding Monomials From A Given Polynomial In Sympy"