How to calculate dot product of two vectors in Python?
Last Updated : 04 Apr, 2025
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,
A = a_1i + a_2j + a_3k
B = b_1i + b_2j + b_3k
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:
DotProduct = a_1 * b_1 + a_2 * b_2 + a_3 * b_3
Example:
Given two vectors A and B as,
A = 3i + 5j + 4k \\ B = 2i + 7j + 5k \\ DotProduct = 3 * 2 + 5 * 7 + 4 * 5 = 6 + 35 + 20 = 61
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:
Python import numpy as np a = 5 b = 7 print(np.dot(a, b))
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:
Python import numpy as np # Taking two 1D array a = 3 + 1j b = 7 + 6j print(np.dot(a, b))
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:
Python 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))
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:
Python 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))
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.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice