在Python中计算多项式的根

在Python中计算多项式的根

要计算多项式的根,可以使用Python Numpy中的polynomial.polyroots()方法。该方法返回多项式的根数组。如果所有的根都是实数,那么输出也是实数,否则为复数。参数c是一个一维数组,表示多项式的系数。

根的估计值是通过伴随矩阵的特征值得到的。远离复平面原点的根可能由于此类值的幂级数的数值不稳定性而产生较大的误差。具有大于1重根的根也会显示较大的误差,因为该级数在这些点附近的值对根的误差相对不敏感。靠近原点的孤立根可能通过几次牛顿法迭代来改进。

步骤

首先,导入所需的库-

from numpy.polynomial import polynomial as P

要计算多项式的根,可以在Python Numpy中使用polynomial.polyroots()方法。

print("Result (roots of a polynomial)...\n",P.polyroots((-1,0,1)))

获取数据类型 −

print("\nType...\n",P.polyroots((-1,0,1)).dtype)

获取形状 –

print("\nShape...\n",P.polyroots((-1,0,1)).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.
print("Result (roots of a polynomial)...\n",P.polyroots((-1,0,1)))

# Get the datatype
print("\nType...\n",P.polyroots((-1,0,1)).dtype)

# Get the shape
print("\nShape...\n",P.polyroots((-1,0,1)).shape)

输出

Result (roots of a polynomial)...
[-1. 1.]

Type...
float64

Shape...
(2,)

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程