v9.1.1
Menu

Angle Between Vectors

mediumFREEVectorsLinear AlgebraCV: Mathematical Foundations

Implement a function to calculate the angle between two vectors a and b in degrees. This task involves understanding vector operations and trigonometric relationships, particularly the dot product and its connection to the cosine of the angle between vectors.

The dot product of two vectors a and b is given by a⋅b=∑i=1naibi\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i, where nn is the dimension of the vectors. The magnitude of a vector a is denoted by ∣∣a∣∣=a⋅a||\mathbf{a}|| = \sqrt{\mathbf{a} \cdot \mathbf{a}}. To find the angle θ\theta between two vectors, we use the formula cos⁡(θ)=a⋅b∣∣a∣∣⋅∣∣b∣∣\cos(\theta) = \frac{\mathbf{a} \cdot \mathbf{b}}{||\mathbf{a}|| \cdot ||\mathbf{b}||}.

Here are the steps to calculate the angle:

  1. Compute the dot product of vectors a and b.
  2. Calculate the magnitudes of vectors a and b.
  3. Use the formula to find cos⁡(θ)\cos(\theta).
  4. Find the angle θ\theta using the inverse cosine function.
cos⁡(θ)=a⋅b∣∣a∣∣⋅∣∣b∣∣\cos(\theta) = \frac{\mathbf{a} \cdot \mathbf{b}}{||\mathbf{a}|| \cdot ||\mathbf{b}||}

This technique is widely used in computer vision for measuring similarity between feature vectors.

Example

Input
angle_between([1, 0], [0, 1])
Output
90.0
Reasoning
  • Inputs: a = [1, 0] and b = [0, 1] are two vectors in the plane. The first points one unit along the xx-axis, the second one unit along the yy-axis.
  • Dot product: pair up matching components and add the products: a⋅b=(1)(0)+(0)(1)=0\mathbf{a}\cdot\mathbf{b} = (1)(0) + (0)(1) = 0.
  • Magnitudes: ∥a∥=12+02=1\|\mathbf{a}\| = \sqrt{1^2 + 0^2} = 1 and ∥b∥=02+12=1\|\mathbf{b}\| = \sqrt{0^2 + 1^2} = 1. Both are unit vectors.
  • Cosine: cos⁡θ=01⋅1=0\cos\theta = \frac{0}{1 \cdot 1} = 0. The only angle in [0°,180°][0°, 180°] with cosine 00 is θ=π2\theta = \frac{\pi}{2} radians, which is π2⋅180°π=90°\frac{\pi}{2} \cdot \frac{180°}{\pi} = 90°.
  • Output: 90.0, the angle in degrees rounded to 2 decimal places. The vectors are perpendicular.
  • Notice: a zero dot product always means 90°90°, whatever the lengths. Parallel vectors give cos⁡θ=1\cos\theta = 1 (0°0°) and opposite vectors give cos⁡θ=−1\cos\theta = -1 (180°180°).

Constraints

  • Both vectors have the same length n where 1 ≤ n ≤ 1000
  • Neither vector is the zero vector
  • Return the angle in degrees, rounded to 2 decimal places

More from CV: Mathematical Foundations

solution.py

Test results

Sign in to run your code against the test cases.