在Python中对多项式以及系数的每一列进行求值

在Python中对多项式以及系数的每一列进行求值

要对在点x处指定根的多项式进行求值,可以使用Python Numpy中的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)

使用Python Numpy中的polynomial.polyvalfromroots()方法来评估由其在x点处的根指定的多项式。

print("\nResult...\n",polyvalfromroots([-2, 1], c, tensor=True))

示例

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=True))

输出

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. 3.]
[ 3. 0.]]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程