How to calculate dot product of two vectors in Python?
dot product or also known as the scalar product is an algebraic operation that takes two equal-length sequences of numbers and returns a single number. Let us given two vectors A and B, and we have to find the dot product of two vectors.
Given that,
Where,
i: the unit vector along the x directions
j: the unit vector along the y directions
k: the unit vector along the z directions
Then the dot product is calculated as:
Example:
Given two vectors A and B as,
Syntax
numpy.dot(vector_a, vector_b, out = None)
Parameters
- vector_a: [array_like] if a is complex its complex conjugate is used for the calculation of the dot product.
- vector_b: [array_like] if b is complex its complex conjugate is used for the calculation of the dot product.
- out: [array, optional] output argument must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b).
Return Value: Dot Product of vectors a and b. if vector_a and vector_b are 1D, then scalar is returned
Example 1:
import numpy as np
a = 5
b = 7
print(np.dot(a, b))
Output
35
Explanation: np.dot(a, b) computes the dot product of a and b. For scalars, it just multiplies them. Here, 5 * 7 = 35.
Example 2:
import numpy as np
# Taking two 1D array
a = 3 + 1j
b = 7 + 6j
print(np.dot(a, b))
Output
(15+25j)
Explanation:
- a = 3 + 1j and b = 7 + 6j are complex numbers.
- np.dot(a, b) computes the dot product of two complex numbers. For complex numbers, the dot product involves multiplying their real and imaginary parts and adding them together.
Example 3:
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]]
print(np.dot(a, b))
Output
[[5 4] [9 6]]
Explanation:
- a and b are 2x2 matrices.
- np.dot(a, b) performs matrix multiplication (also known as the dot product for matrices). The matrix product is computed by taking the dot product of rows of the first matrix with columns of the second matrix.
Example 4:
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]]
print(np.dot(b, a))
Output
[[2 4] [6 9]]
Explanation:
- a and b are 2x2 matrices
- np.dot(b, a) performs matrix multiplication. This operation computes the product of b and a by taking the dot product of rows of b with columns of a.