使用 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,)
广告