在Python中对多项式进行点求值和x在r的列上广播求值
在Python的Numpy中,使用polynomial.polyvalfromroots()方法来求解由其根点x指定的多项式。第一个参数是x。如果x是一个列表或元组,它会被转换成ndarray,否则保持不变,并被视为标量。无论哪种情况,x或其元素必须支持自身和r的元素的加法和乘法。
第二个参数r是根点数组。如果r是多维的,第一个索引是根索引,而剩余的索引则列举了多个多项式。例如,在二维情况下,每个多项式的根可以被认为保存在r的列中。
第三个参数是张量。如果为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处指定的多项式,可以使用Python的Numpy中的polynomial.polyvalfromroots()方法。
print("\nResult...\n",polyvalfromroots([-2, 1], c, tensor=False))
示例
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([-2, 1], c, tensor=False))
输出
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...
[-0. 0.]