List of coefficients to polynomial

和自甴很熟 提交于 2021-01-27 06:08:18

问题


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.


回答1:


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')



回答2:


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.




回答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')


来源:https://stackoverflow.com/questions/32406651/list-of-coefficients-to-polynomial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!