Nico Schlömer
Nico Schlömer

Reputation: 58721

construct sympy.poly from coefficients and monomials

I have sympy.poly of which I'd like to conjugate all coefficients. That's easy enough to do, but how do I re-assemble a polynomial from the new monomials and coefficients?

MWE:

from sympy import symbols, poly, I

x = symbols("x")

p = poly(x ** 2 + I, [x])

print(p.coeffs())
conj_coeffs = [c.conjugate() for c in p.coeffs()]
print(conj_coeffs)

# poly(p.coeffs(), p.monoms()) ??
[1, I]
[1, -I]

Upvotes: 2

Views: 974

Answers (3)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

A Poly has an equivalent dict representation:

In [17]: p = Poly(x**2 + 2*x, x)                                                                                                  

In [18]: p                                                                                                                        
Out[18]: Poly(x**2 + 2*x, x, domain='ZZ')

In [19]: p.as_dict()                                                                                                              
Out[19]: {(1,): 2, (2,): 1}

The dict maps a tuple of monomial powers to the coefficient.

The Poly.from_dict class method can construct a Poly from this dict representation. The invariant is:

In [22]: p == Poly.from_dict({m: p.coeff_monomial(m) for m in p.monoms()}, p.gens)                                                
Out[22]: True

If you want to alter the coefficients you can intercept p.coeff_monomial(m) and replace it with something else e.g. conjugate(p.coeff_monomial(m)).

Upvotes: 2

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

How would you like the output, would this be useful?

res = [str(coeff) + 'x^' + str(power[0])
       for coeff, power in zip(conj_coeffs, p.monoms())
       ]

print(' + '.join(res))

Returning:

1x^2 - Ix^0

Upvotes: 0

smichr
smichr

Reputation: 18979

Poly can accept a list of all coefficients:

>>> Poly([1,0,I],x)
Poly(x**2 + I, x, domain='EX')
>>> _.all_coeffs()
[1, 0, I]
>>> Poly([i.conjugate() for i in _],x)
Poly(x**2 - I, x, domain='EX')

Upvotes: 2

Related Questions