使用 Python 生成帶有給定根的單式多項式
若要生成帶有給定根的單式多項式,請使用 Python Numpy 中的 polynomial.polyfromroots() 方法。該方法返回多項式係數的 1 維陣列。如果所有根都是實數,則結果也是實數,否則為複數。引數 roots 包含根的序列。
步驟
首先,匯入所需庫 −
from numpy.polynomial import polynomial as P
生成單式多項式 −
print("Result...\n",P.polyfromroots((-1,0,1)))
獲取資料型別 −
print("\nType...\n",P.polyfromroots((-1,0,1)).dtype)
獲取形狀 −
print("\nShape...\n",P.polyfromroots((-1,0,1)).shape)
示例
from numpy.polynomial import polynomial as P # To generate a monic polynomial with given roots, use the polynomial.polyfromroots() method in Python Numpy. # The method returns the 1-D array of the polynomial’s coefficients If all the roots are real, then out is also real, otherwise it is complex. # The parameter roots are the sequence containing the roots. # x(x - 1)(x + 1) = x^3 - x print("Result...\n",P.polyfromroots((-1,0,1))) # Get the datatype print("\nType...\n",P.polyfromroots((-1,0,1)).dtype) # Get the shape print("\nShape...\n",P.polyfromroots((-1,0,1)).shape)
輸出
Result... [ 0. -1. 0. 1.] Type... float64 Shape... (4,)
廣告