📜  如何在Python中计算两个向量的点积?

📅  最后修改于: 2022-05-13 01:55:31.968000             🧑  作者: Mango

如何在Python中计算两个向量的点积?

在数学中,点积或也称为标量积是一种代数运算,它采用两个等长的数字序列并返回一个数字。让我们给定两个向量AB,我们必须找到两个向量的点积。

鉴于,

A = a_1i + a_2j + a_3k

和,

B = b_1i + b_2j + b_3k

然后点积计算为:

DotProduct = a_1 * b_1 + a_2 * b_2 + a_3 * b_3

例子:

给定两个向量 A 和 B,

A = 3i + 5j + 4k \\ B = 2i + 7j + 5k \\ DotProduct = 3 * 2 + 5 * 7 + 4 * 5 = 6 + 35 + 20 = 61

Python中两个向量的点积

Python提供了一种非常有效的方法来计算两个向量的点积。通过使用 NumPy 模块中可用的numpy.dot()方法,可以做到这一点。

示例 1:

Python
# Python Program illustrating
# dot product of two vectors
 
# Importing numpy module
import numpy as np
 
# Taking two scalar values
a = 5
b = 7
 
# Calculating dot product using dot()
print(np.dot(a, b))


Python
# Python Program illustrating
# dot product of two vectors
 
# Importing numpy module
import numpy as np
 
# Taking two 1D array
a = 3 + 1j
b = 7 + 6j
 
# Calculating dot product using dot()
print(np.dot(a, b))


Python
# Python Program illustrating
# dot product of two vectors
 
# Importing numpy module
import numpy as np
 
# Taking two 2D array
# For 2-D arrays it is the matrix product
a = [[2, 1], [0, 3]]
b = [[1, 1], [3, 2]]
 
# Calculating dot product using dot()
print(np.dot(a, b))


Python
# Python Program illustrating
# dot product of two vectors
 
# Importing numpy module
import numpy as np
 
# Taking two 2D array
# For 2-D arrays it is the matrix product
a = [[2, 1], [0, 3]]
b = [[1, 1], [3, 2]]
 
# Calculating dot product using dot()
# Note that here I have taken dot(b, a)
# Instead of dot(a, b) and we are going to
# get a different output for the same vector value
print(np.dot(b, a))


输出:

35

示例 2:

Python

# Python Program illustrating
# dot product of two vectors
 
# Importing numpy module
import numpy as np
 
# Taking two 1D array
a = 3 + 1j
b = 7 + 6j
 
# Calculating dot product using dot()
print(np.dot(a, b))

输出:

(15+25j)

示例 3:

Python

# Python Program illustrating
# dot product of two vectors
 
# Importing numpy module
import numpy as np
 
# Taking two 2D array
# For 2-D arrays it is the matrix product
a = [[2, 1], [0, 3]]
b = [[1, 1], [3, 2]]
 
# Calculating dot product using dot()
print(np.dot(a, b))

输出:

[[5 4]
 [9 6]]

示例 4:

Python

# Python Program illustrating
# dot product of two vectors
 
# Importing numpy module
import numpy as np
 
# Taking two 2D array
# For 2-D arrays it is the matrix product
a = [[2, 1], [0, 3]]
b = [[1, 1], [3, 2]]
 
# Calculating dot product using dot()
# Note that here I have taken dot(b, a)
# Instead of dot(a, b) and we are going to
# get a different output for the same vector value
print(np.dot(b, a))

输出:

[[2 4]
 [6 9]]