在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,)

更新於:2022年3月8日

3K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.