This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: NumPy recap and exercises

Angle between two vectors

face Joe Stacey Josiah Wang

Here is another Math question!

Challenge #4

Use NumPy to compute the angle (in degrees) between the two vectors x and y. You will need to:

  1. Compute the unit vector for x and y (Hint: Use your solutions from the previous challenge!)
  2. Compute the dot product of these two vectors (giving you \cos(x))
  3. Compute the \arccos of \cos(x) to get the angle in radians
  4. Covert the angle from radians to degrees
import numpy as np

x = np.array([3, 4, 1, 5])
y = np.array([4, 1, 1, -1])
angle_deg = ????? 
assert np.isclose(angle_deg, 67.32549258300477)

import numpy as np

x = np.array([3, 4, 1, 5])
y = np.array([4, 1, 1, -1])
unit_x = x / np.linalg.norm(x)
unit_y = y / np.linalg.norm(y)
angle_rad = np.arccos(np.dot(unit_x, unit_y))
angle_deg = np.degrees(angle_rad)