如何在Python中计算两个向量的点积
在数学中,点积或也称为标量积是一个代数运算,它将两个等长的数字序列取出并返回一个数字。让我们给两个向量A和B,我们必须找到两个向量的点积。
鉴于此,
和,
其中,
**i: **沿x方向的单位矢量
j:沿y方向的单位矢量
k:沿Z方向的单位矢量
那么点积的计算方法是:
示例:
给出两个向量A和B为。
Python中两个矢量的点积
Python 提供了一种非常有效的方法来计算两个向量的点积。通过使用NumPy模块中的numpy.dot()方法,可以做到这一点。
语法:
numpy.dot(vector_a, vector_b, out = None)
参数:
vector_a: [array_like] 如果a是复数,它的复数共轭将用于计算点积。
vector_b: [array_like] 如果b是复数,它的复数共轭将用于点乘的计算。
out: [array, optional] 输出参数必须是C-连续的,其dtype必须是dot(a,b)所返回的dtype。
返回:
向量a和b的点积。如果向量a和向量b是1D,则返回标量。
示例 1:
# 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))
输出:
35
示例 2:
# 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 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 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]]