在 Python 中返回两个向量的点积

pythonnumpyserver side programmingprogramming更新于 2024/5/10 15:08:17

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

该方法返回 a 和 b 的点积。可以是 int、float 或复数,具体取决于 a 和 b 的类型。第一个参数是 a。如果 a 是复数,则在计算点积之前先取复共轭。 b 是点积的第二个参数。

步骤

首先,导入所需的库 −

import numpy as np

使用 array() 方法创建两个 numpy 一维数组 −

arr1 = np.array([2+3j,5+6j])
arr2 = np.array([9+10j,11+12j])

显示数组 −

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("\n结果...\n",np.vdot(arr1, arr2))

示例

import numpy as np

# 使用 array() 方法创建两个 numpy 一维数组
arr1 = np.array([2+3j,5+6j])
arr2 = np.array([9+10j,11+12j])

# 显示数组
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("\n结果...\n",np.vdot(arr1, arr2))

输出

Array1...
[2.+3.j 5.+6.j]

Array2...
[ 9.+10.j 11.+12.j]

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(2,)

Shape of Array2...
(2,)

结果...
(175-13j)


相关文章


有用资源