Python中使用愛因斯坦求和約定進行向量外積


要使用愛因斯坦求和約定計算向量的外積,請在Python中使用numpy.einsum()方法。第一個引數是下標,它指定作為逗號分隔的下標標籤列表的求和下標。第二個引數是運算元,這些是操作的陣列。

einsum()方法對運算元評估愛因斯坦求和約定。使用愛因斯坦求和約定,許多常見的多分量線性代數陣列操作可以用簡單的方式表示。在隱式模式下,einsum計算這些值。

在顯式模式下,einsum透過停用或強制對指定的下標標籤進行求和,提供了進一步的靈活性來計算可能不被認為是經典愛因斯坦求和運算的其他陣列運算。

步驟

首先,匯入所需的庫:

import numpy as np

使用arange()和reshape()方法建立一個numpy陣列:

arr = np.arange(5)

顯示陣列:

print("Our Array...\n",arr)

檢查維度:

print("\nDimensions of our Array...\n",arr.ndim)

獲取資料型別:

print("\nDatatype of our Array object...\n",arr.dtype)

獲取形狀:

print("\nShape of our Array object...\n",arr.shape)

要使用愛因斯坦求和約定計算向量的外積,請使用numpy.einsum()方法。第一個引數是下標,它指定作為逗號分隔的下標標籤列表的求和下標。第二個引數是運算元,這些是操作的陣列:

print("\nResult (outer product)...\n",np.einsum('i,j', np.arange(2)+1, arr))

示例

import numpy as np

# Creating a numpy array using the arange() and reshape() method
arr = np.arange(5)

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To compute outer product of vectors with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (outer product)...\n",np.einsum('i,j', np.arange(2)+1, arr))

輸出

Our Array...
[0 1 2 3 4]

Dimensions of our Array...
1

Datatype of our Array object...
int64

Shape of our Array object...
(5,)

Result (outer product)...
[[0 1 2 3 4]
[0 2 4 6 8]]

更新於:2022年3月2日

511 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.