How to calculate dot product of two vectors in Python?
Published on Aug. 22, 2023, 12:15 p.m.
To calculate the dot product of two vectors in Python, you can use the NumPy library, which provides a convenient dot()
method for this purpose. Here’s an example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
dot_product = np.dot(a, b)
print(dot_product)
In this example, we define two NumPy arrays a
and b
to represent our vectors. We then call the dot()
method of the NumPy library to calculate the dot product of a
and b
and store the result in the dot_product
variable. Finally, we print the value of dot_product
.
The dot product of two vectors a
and b
is calculated as a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1]
.
Alternatively, if you do not want to use NumPy, you can implement the dot product calculation yourself using a list comprehension, like this:
a = [1, 2, 3]
b = [4, 5, 6]
dot_product = sum([a[i] * b[i] for i in range(len(a))])