List of coefficients to polynomial
Asked Answered
C

3

7

How do I create a polynomial out of a list of coefficients in SymPy?

For example, given a list [1, -2, 1] I would like to get Poly(x**2 - 2*x + 1). I tried looking at the docs but could not find anything close to it.

Casein answered 4/9, 2015 at 21:10 Comment(2)
It's unfortunate that your example list is mirrored -- that makes it hard to tell which element is the coefficient of x**0 and which is the coefficient for x**2.Dennadennard
@Dennadennard It doesn't matter: take any ordering which suits you. What I try to say is that I could easily do [::-1 if I needed to.Casein
G
10

You could use Poly.from_list to construct the polynomial:

>>> x = sympy.Symbol('x')
>>> sympy.Poly.from_list([1, -2, 1], gens=x)
Poly(x**2 - 2*x + 1, x, domain='ZZ')
Gammon answered 4/9, 2015 at 21:16 Comment(2)
The only documentation I found for this is docs.sympy.org/0.7.1/modules/polys/reference.html which only mentions from_list() as a class method, then had to click on the source link to find out the class in question is Poly and still found no examples of this or other Poly class methods. Is there any better documentation for sympy.polys.polytools.Poly methods?Ovaritis
@TrisNefzger - I've had a look but not found any additional documentation for the method, unfortunately. I guess as SymPy is still a relatively young project the documentation still has some catching up to do...Gammon
D
3

It looks to me like you would do something like:

from sympy.abc import x
from sympy import poly
lst = [1, -2, 1]
poly(sum(coef*x**i for i, coef in enumerate(reversed(lst))))

Of course, you don't depending on which coefficient maps to x**0, you might not need the reversed in the above.

Dennadennard answered 4/9, 2015 at 21:14 Comment(0)
B
3

This simpler alternative works for me (Sympy 0.7.6.1):

>>> from sympy import Symbol, Poly
>>> x = Symbol('x')
>>> Poly([1,2,3], x)
Poly(x**2 + 2*x + 3, x, domain='ZZ')
Bohi answered 13/9, 2015 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.