评估爱因斯坦的两个多维NumPy数组的求和惯例
在Python中,我们可以使用NumPy包的einsum()函数来计算两个给定多维数组的爱因斯坦求和惯例。
语法: numpy.einsum(subscripts, *operands, out=None)
参数:
副标题 : str
指定用于求和的下标,以逗号分隔的下标标签列表。除非包含显式指标’->’以及精确输出形式的下标标签,否则将进行隐式(经典的爱因斯坦求和)计算。
操作数 : 类似数组的列表
这些是操作的数组。
输出: ndarray, optional
如果提供,计算就会进入这个数组。
返回:基于爱因斯坦求和惯例的计算。
例子1:爱因斯坦的两个2X2矩阵的求和惯例
# Importing library
import numpy as np
# Creating two 2X2 matrix
matrix1 = np.array([[1, 2], [0, 2]])
matrix2 = np.array([[0, 1], [3, 4]])
print("Original matrix:")
print(matrix1)
print(matrix2)
# Output
result = np.einsum("mk,kn", matrix1, matrix2)
print("Einstein’s summation convention of the two matrix:")
print(result)
输出:
Original matrix:
[[1 2]
[0 2]]
[[0 1]
[3 4]]
Einstein’s summation convention of the two matrix:
[[6 9]
[6 8]]
例子2:爱因斯坦的两个3X3矩阵的求和惯例
# Importing library
import numpy as np
# Creating two 3X3 matrix
matrix1 = np.array([[2, 3, 5], [4, 0, 2], [0, 6, 8]])
matrix2 = np.array([[0, 1, 5], [3, 4, 4], [8, 3, 0]])
print("Original matrix:")
print(matrix1)
print(matrix2)
# Output
result = np.einsum("mk,kn", matrix1, matrix2)
print("Einstein’s summation convention of the two matrix:")
print(result)
输出:
Original matrix:
[[2 3 5]
[4 0 2]
[0 6 8]]
[[0 1 5]
[3 4 4]
[8 3 0]]
Einstein’s summation convention of the two matrix:
[[49 29 22]
[16 10 20]
[82 48 24]]
例子3:爱因斯坦的两个4X4矩阵的求和惯例
# Importing library
import numpy as np
# Creating two 4X4 matrix
matrix1 = np.array([[1, 2, 3, 5], [4, 4, 0, 2],
[0, 1, 6, 8], [0, 5, 6, 9]])
matrix2 = np.array([[0, 1, 9, 2], [3, 3, 4, 4],
[1, 8, 3, 0], [5, 2, 1, 6]])
print("Original matrix:")
print(matrix1)
print(matrix2)
# Output
result = np.einsum("mk,kn", matrix1, matrix2)
print("Einstein’s summation convention of the two matrix:")
print(result)
输出:
Original matrix:
[[1 2 3 5]
[4 4 0 2]
[0 1 6 8]
[0 5 6 9]]
[[0 1 9 2]
[3 3 4 4]
[1 8 3 0]
[5 2 1 6]]
Einstein’s summation convention of the two matrix:
[[34 41 31 40]
[22 20 54 36]
[49 67 30 52]
[66 81 47 74]]