Dot Product in 2D with Python

Talking about dot products in linear algebra can be really a subject of hours, but long story short this is probably the minimal knowledge you can live with:

  • The dot product (inner product) is an operation on 2 vectors that return a scalar.
    E.g., given 2 vectors u and v, have their result np.dot(u, v)  to be a real number.
  • The dot product works on vectors in 2D, 3D or other dimensions.
  • The dot product is measuring “how aligned” 2 vectors are.
    • In 2D space, parallel vectors, pointing in the same direction, have dot products of 1.
    • In 2D space, parallel vectors, pointing in the opposite directions, have dot products of -1.
    • Perpendicular vectors, forming a 90-degree angle, always produce a dot product of 0 due to the cosine of the angle being 0.
    • For vectors with arbitrary angles between them, the dot product varies according to the cosine of the angle formed, resulting in values other than 0, 1, or -1.

Pretty much that is just the top of the iceberg, but it is good to illustrate this a bit:

import numpy as np
import matplotlib.pyplot as plt

v1 = np.array([1, 0])
v2 = np.array([0, 1])

v3 = np.array([0.6, 0.8])
v31 = np.array([0.8, -0.6])

v4 = np.array([0.6, -0.8])
v5 = np.array([1, 0])
v6 = np.array([-1, 0])

# Plotting
plt.figure(figsize=(5, 5))
# v1, v2, v3, v31, v4, v5, v6

for i, v in enumerate([v3, v31, v4]):
    plt.quiver(0, 0, v[0], v[1], angles='xy', scale_units='xy', scale=1, color='C'+str(i), label='vector' + str(i+1))

plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.axhline(0, color='black',linewidth=0.7)
plt.axvline(0, color='black',linewidth=0.7)
plt.grid(color = 'gray', linestyle = '--', linewidth = 0.5)
plt.title('Dot Products in Linear Algebra')
plt.legend()
plt.show()

Returns the following, where it is obvious which vectors are perpendicular:

Vector 2 and Vector 1 are perpendicular, with degree between them equalling 90 and a dot product of 0.
Dot Product in 2D - briefly explained with Python

Thank you for your interest and enjoy the linear algebra and your day!