How to Compute the Angle Between Vectors Using Python

The angle between two vectors represents the spatial relationship or orientation between them. A smaller angle means the vectors are more closely aligned, while a larger angle indicates they are pointing in more different directions.

Let’s begin by visualizing couple vectors:

# Visualize 2D Vectors

import numpy as np
import matplotlib.pyplot as plt

# Define vectors for each scenario
vectors = {
'First Set Of Vectors': np.array([[2, 0], [2, 0]]),
'Second Set Of Vectors': np.array([[2, 0], [0, 2]]),
'Third Set Of Vectors': np.array([[2, 0], [-2, 0]]),
'Fourth Set Of Vectors': np.array([[2.5, 0.5], [-2.5, 1.5]])
}

# Function to plot vectors
def plot_vectors(vectors):
"""Plot each set of vectors."""
fig, axs = plt.subplots(1, len(vectors), figsize=(15, 5))
colors = ['blue', 'red']  # Colors for the two vectors in each subplot

for ax, (title, vec_pair) in zip(axs, vectors.items()):
for vec, color in zip(vec_pair, colors):
ax.quiver(0, 0, vec[0], vec[1], color=color, angles='xy',
scale_units='xy', scale=1, width=0.03)

ax.set_xlim(-3.5, 3.5)
ax.set_ylim(-1.5, 3.5)
ax.set_title(title, fontsize=14)
ax.axhline(0, color='black', linewidth=0.5)
ax.axvline(0, color='black', linewidth=0.5)
ax.grid(True)

plt.show()

# Execute the plotting function
plot_vectors(vectors)


The code above will output the following four 2D vectors:

With the plots above, you can visually grasp the concept of angles between vectors. Each set of vectors in the plot represents different scenarios we might encounter:

• First Set Of Vectors: Both vectors point in the same direction along the x-axis, illustrating an angle of 0 degrees. This is an example of collinearity where vectors align perfectly.
• Second Set Of Vectors: These vectors are perpendicular, represented by an angle of 90 degrees. Such orthogonal vectors often come into play in scenarios requiring independence or non-overlapping dimensions.
• Third Set Of Vectors: Here, the vectors lie on the same line but point in opposite directions, creating an angle of 180 degrees, the maximum angle possible between two vectors.
• Fourth Set Of Vectors: This set shows two vectors at a less obvious angle, demonstrating the typical scenario where calculating the angle quantitatively becomes crucial.

The formula commonly used to calculate the angle between vectors is expressed as follows:

The cosine function relates the angle to the dot product and the magnitudes. The result of the cosine function, when inverted through the arccos function, gives us the angle θ in radians. This angle can be converted to degrees, which are often more intuitive to interpret.

By applying this formula, we can determine the exact angle between any two vectors, as long as we can compute their dot products and magnitudes. Let’s now see how this formula is implemented in Python to calculate the angles between our example vectors.

# Function to compute angle using the dot product and magnitude
def compute_angle_with_dot_product(vectors):
"""Calculate the angle and dot product between two vectors."""
for title, vec_pair in vectors.items():
u, v = vec_pair
dot_product = np.dot(u, v)
magnitude_u = np.linalg.norm(u)
magnitude_v = np.linalg.norm(v)
angle = np.degrees(np.arccos(dot_product / (magnitude_u * magnitude_v)))
print(title)
print(f"The angle is {angle:.2f} degrees")
print(f"The dot product is {dot_product:.2f}")
print()

# Execute the function to compute angles
compute_angle_with_dot_product(vectors)


This code will output:

First Set Of Vectors
The angle is 0.00 degrees
The dot product is 4.00

Second Set Of Vectors
The angle is 90.00 degrees
The dot product is 0.00

Third Set Of Vectors
The angle is 180.00 degrees
The dot product is -4.00

Fourth Set Of Vectors
The angle is 137.73 degrees
The dot product is -5.50


An angle of 90° signifies that vectors are orthogonal, or perpendicular, to each other. This relationship is characterized by a dot product of zero, a distinctive property of orthogonal vectors, as demonstrated by our ‘Second Set Of Vectors’ shown earlier.

We can extend the same methodology to compute angles between vectors in higher-dimensional spaces.

# Expand to Higher Dimensions
vectors_XD = {
'3D Vectors': np.array([[1, 2, 3], [4, 5, 6]]),
'4D Vectors': np.array([[1, 2, 3, 4], [5, 6, 7, 8]]),
'5D Vectors': np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
}

compute_angle_with_dot_product(vectors_XD)


The Python code above demonstrates how we calculate the angle between vectors that reside in three, four, and even five-dimensional spaces:

3D Vectors
The angle is 12.93 degrees
The dot product is 32.00

4D Vectors
The angle is 14.34 degrees
The dot product is 70.00

5D Vectors
The angle is 15.21 degrees
The dot product is 130.00


While Python libraries like NumPy and SciPy do not provide a direct method for calculating vector angles, they offer the essential building blocks necessary to enhance our understanding and computational ability when determining the angles between vectors.