返回Python中两个多维向量的点积


要返回两个多维向量的点积,请在Python中使用numpy.vdot()方法。vdot(a, b)函数处理复数的方式与dot(a, b)不同。如果第一个参数是复数,则在计算点积时使用第一个参数的复共轭。vdot处理多维数组的方式与dot不同:它不会执行矩阵乘积,而是首先将输入参数展平为一维向量。因此,它应该只用于向量。

该方法返回a和b的点积。根据a和b的类型,可以是整数、浮点数或复数。第一个参数是a。如果a是复数,则在计算点积之前取其复共轭。b是点积的第二个参数。

步骤

首先,导入所需的库:

import numpy as np

使用array()方法创建两个NumPy多维数组:

arr1 = np.array([[5, 10],[15, 20]])
arr2 = np.array([[3, 6],[9, 12]])

显示数组:

print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

检查两个数组的维度:

print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

检查两个数组的形状:

print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

要返回两个多维向量的点积,请在Python中使用numpy.vdot()方法:

print("\nResult...\n",np.vdot(arr1, arr2))

示例

import numpy as np

# Creating two numpy Multi-Dimensional array using the array() method
arr1 = np.array([[5, 10],[15, 20]])
arr2 = np.array([[3, 6],[9, 12]])

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# To return the dot product of two multi-dimensional vectors, use the numpy.vdot() method in Python.
print("\nResult...\n",np.vdot(arr1, arr2))

输出

Array1...
[[ 5 10]
[15 20]]

Array2...
[[ 3 6]
[ 9 12]]

Dimensions of Array1...
2

Dimensions of Array2...
2

Shape of Array1...
(2, 2)

Shape of Array2...
(2, 2)

Result...
450

更新于:2022年3月1日

407 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告