在Python中使用多维根数组对给定点x求解多项式
要对在给定点x处的多项式进行求解,可以使用Python Numpy中的polynomial.polyvalfromroots()方法。第一个参数是x。如果x是一个列表或元组,它将被转换为ndarray,否则将保持不变并被视为标量。在任何情况下,x或其元素必须支持与自身和r的元素的加法和乘法运算。
第二个参数r是一个根数组。如果r是多维的,第一个索引是根索引,而其他索引枚举多个多项式。例如,在二维情况下,每个多项式的根可以看作是存储在r的列中。
第三个参数是tensor。如果设置为True,则根数组的形状在右侧扩展,每个x的维度都添加一个。对于此操作,标量的维度为0。结果是r中的每一列系数都对x的每个元素进行求解。如果设置为False,则将x广播到r的列用于求解。当r是多维的时,此关键字非常有用。默认值为True。
步骤
首先,导入所需的库−
from numpy.polynomial.polynomial import polyvalfromroots
import numpy as np
创建一个多维系数数组 –
c = np.arange(-2, 2).reshape(2,2)
显示数组 –
print("Our Array...\n",c)
检查尺寸 −
print("\nDimensions of our Array...\n",c.ndim)
获取数据类型 –
print("\nDatatype of our Array object...\n",c.dtype)
获取形状 –
print("\nShape of our Array object...\n",c.shape)
要评估在点x处指定根的多项式,请使用polynomial.polyvalfromroots()方法-
print("\nResult...\n",polyvalfromroots(1, c))
示例
from numpy.polynomial.polynomial import polyvalfromroots
import numpy as np
# Create an array of multidimensional coefficients
c = np.arange(-2, 2).reshape(2,2)
# Display the array
print("Our Array...\n",c)
# Check the Dimensions
print("\nDimensions of our Array...\n",c.ndim)
# Get the Datatype
print("\nDatatype of our Array object...\n",c.dtype)
# Get the Shape
print("\nShape of our Array object...\n",c.shape)
# To evaluate a polynomial specified by its roots at points x, use the polynomial.polyvalfromroots() method in Python Numpy
print("\nResult...\n",polyvalfromroots(1, c))
输出
Our Array...
[[-2 -1]
[ 0 1]]
Dimensions of our Array...
2
Datatype of our Array object...
int64
Shape of our Array object...
(2, 2)
Result...
[3. 0.]