在Python中计算给定复根的多项式的根
要计算多项式的根,可以使用Python的Numpy库中的polynomial.polyroots()方法。该方法返回多项式的根的数组。如果所有的根都是实数,则结果也是实数,否则是复数。参数c是一个一维数组,包含多项式的系数。
根的估计值通过伴随矩阵的特征值来获取,远离复平面原点的根可能由于对该值的幂级数的数值不稳定性而产生较大误差。具有大于1次重数的根也会显示较大的误差,因为在这些点附近的级数值对根的误差相对不敏感。靠近原点的孤立根可以通过几次牛顿迭代法进行改进。
步骤
首先,导入所需的库-
from numpy.polynomial import polynomial as P
要计算多项式的根,请使用Python Numpy中的polynomial.polyroots()方法-
j = complex(0,1)
print("Result (roots of a polynomial)...\n",P.polyroots((-j,j)))
获取数据类型 –
print("\nType...\n",P.polyroots((-j, j)).dtype)
获得形状−
print("\nShape...\n",P.polyroots((-j, j)).shape)
示例
from numpy.polynomial import polynomial as P
# To compute the roots of a polynomials, use the polynomial.polyroots() method in Python Numpy.
# The method returns an array of the roots of the polynomial. If all the roots are real, then out is also real, otherwise it is complex.
# The parameter, c is a 1-D array of polynomial coefficients.
j = complex(0,1)
print("Result (roots of a polynomial)...\n",P.polyroots((-j,j)))
# Get the datatype
print("\nType...\n",P.polyroots((-j, j)).dtype)
# Get the shape
print("\nShape...\n",P.polyroots((-j, j)).shape)
输出
Result (roots of a polynomial)...
[1.+0.j]
Type...
complex128
Shape...
(1,)