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.
Polynomial coefficients are the numbers that come before a term. Terms usually have a number and a variable (e.g. 2 x 2 2x^2 2x2, where 2 is the number, and x is the variable). The number portion is the coefficient.
In mathematics, a polynomial is an expression consisting of indeterminates (also called variables) and coefficients, that involves only the operations of addition, subtraction, multiplication, and positive-integer powers of variables. An example of a polynomial of a single indeterminate x is x2 − 4x + 7.
The constant coefficient is the coefficient not attached to variables in an expression. For example, the constant coefficients of the expressions above are the number 3 and the parameter c, respectively.
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With