Introduction to NumPy and Matplotlib
Chapter 8: NumPy recap and exercises
Angle between two vectors
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:
- Compute the unit vector for
x
andy
(Hint: Use your solutions from the previous challenge!) - Compute the dot product of these two vectors (giving you \cos(x))
- Compute the \arccos of \cos(x) to get the angle in radians
- 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)