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.