在 Python 中評估多項式,並針對 x 中的每個元素評估 r 中係數的每一列。


要在點 x 處評估由其根指定的多個項式,請使用 Python NumPy 中的 `polynomial.polyvalfromroots()` 方法。第一個引數是 x。如果 x 是列表或元組,則將其轉換為 ndarray;否則,它將保持不變並被視為標量。無論哪種情況,x 或其元素都必須支援自身以及 r 的元素之間的加法和乘法運算。

第二個引數 r 是根的陣列。如果 r 是多維的,則第一個索引是根索引,其餘索引列舉多個多項式。例如,在二維情況下,每個多項式的根可以認為儲存在 r 的列中。

第三個引數是 tensor。如果為 True,則根陣列的形狀將在右側擴充套件為 1,每個維度一個 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=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.]]

更新於:2022年2月28日

瀏覽量:157

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.