Angle Between Vectors
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, where n is the dimension of the vectors. The magnitude of a vector a is denoted by ∣∣a∣∣=a⋅a. To find the angle θ between two vectors, we use the formula cos(θ)=∣∣a∣∣⋅∣∣b∣∣a⋅b.
Here are the steps to calculate the angle:
- Compute the dot product of vectors a and b.
- Calculate the magnitudes of vectors a and b.
- Use the formula to find cos(θ).
- Find the angle θ using the inverse cosine function.
This technique is widely used in computer vision for measuring similarity between feature vectors.
Example:
angle_between([1, 0], [0, 1])
90.00
Step-by-step calculation using the angle formula:
θ=arccos(∥a∥×∥b∥a⋅b)
-
Compute dot product: a⋅b=(1×0)+(0×1)=0
-
Compute magnitudes: ∥a∥=12+02=1 ∥b∥=02+12=1
-
Apply the formula: cos(θ)=1×10=0
-
Find the angle: θ=arccos(0)=90°
-
Result: 90.00°
The vectors [1,0] and [0,1] are the standard basis vectors pointing along the x and y axes respectively, which are perpendicular (90° apart).
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
The angle between two vectors is defined as the geometric angle that separates their directions in space, independent of their lengths. For vectors \mathbf{a} and \mathbf{b}, this angle \theta is computed via the dot product, which links algebraic operations on coordinates to geometric concepts like length and angle. In Euclidean space, the dot product captures how much one vector “points in the direction” of another.
Formally, the dot product satisfies
a⋅b=∥a∥∥b∥cosθ,where ∥\mathbf{a}∥ and ∥\mathbf{b}∥ are the vector magnitudes. Rearranging gives
θ=arccos(∥a∥∥b∥a⋅b).In computer vision, this is widely used to measure similarity between feature descriptors (e.g., embeddings, SIFT-like features) and to compare orientations (e.g., normals, motion vectors).
1. Background Knowledge
- Dot product (inner product) For vectors in Rn,
Geometrically, this equals ∥\mathbf{a}∥∥\mathbf{b}∥cos\theta.
-
If \mathbf{a}⋅\mathbf{b}>0: angle <90∘ (acute).
-
If \mathbf{a}⋅\mathbf{b}=0: vectors are orthogonal.
-
If \mathbf{a}⋅\mathbf{b}<0: angle >90∘ (obtuse).
-
Norm (magnitude) of a vector
This is the Euclidean length. The denominator ∥\mathbf{a}∥∥\mathbf{b}∥ normalizes for length so the angle depends only on direction, not scale.
2. Algorithm / Approach
General pattern to compute the angle between vectors:
- Compute the dot product of the two vectors.
- Compute their magnitudes (Euclidean norms).
- Compute the cosine of the angle as
- Apply inverse cosine (arccos) to get the angle in radians.
- Convert radians to degrees if required:
This same pattern appears in similarity measures, e.g. cosine similarity is just the value cos\theta without the final arccos.
3. Step-by-Step Strategy
Assume vectors are given as arrays/lists of numbers of equal length n.
- Check dimensions
- Ensure both vectors have the same length.
- Handle or report error if not.
- Compute dot product
dot = 0.0
for i in range(n):
dot += a[i] * b[i]
- Compute magnitudes
import math
norm_a_sq = 0.0
norm_b_sq = 0.0
for i in range(n):
norm_a_sq += a[i] * a[i]
norm_b_sq += b[i] * b[i]
norm_a = math.sqrt(norm_a_sq)
norm_b = math.sqrt(norm_b_sq)
- Guard against zero vectors
- If norm_a == 0 or norm_b == 0, the angle is undefined (directionless vector). Decide how your problem wants this handled (e.g., raise error, return 0, etc.).
- Compute cosine of angle
cos_theta = dot / (norm_a * norm_b)
- Clamp for numerical stability
cos_theta = max(-1.0, min(1.0, cos_theta))
- Compute angle in radians and convert to degrees
theta_rad = math.acos(cos_theta)
theta_deg = theta_rad * 180.0 / math.pi
- Return θ in degrees as the final result.
4. Common Pitfalls
-
Zero-length vectors Division by zero occurs if ∥\mathbf{a}∥=0 or ∥\mathbf{b}∥=0. The angle is not defined, so you must explicitly handle this case.
-
Floating-point precision issues Due to rounding, cos_theta might become slightly > 1 or < -1 (e.g. 1.0000000002), causing acos to return NaN. Clamping cos_theta to [−1,1] avoids this.
-
Radians vs degrees confusion Most math libraries return angles in radians. Don’t forget to convert to degrees if the problem specifically asks for degrees.
-
Mismatched dimensions Failing to ensure both vectors have the same length leads to incorrect results or runtime errors.
5. Time & Space Complexity
Let n be the dimension of the vectors.
-
Time Complexity
-
Dot product: O(n)
-
Norm computations: O(n)
-
Remaining operations (divisions, sqrt, acos, conversion): O(1) Overall: O(n).
-
Space Complexity
-
Only a constant number of scalar variables used (dot, norms, etc.).
-
No extra data structures proportional to n. Overall: O(1) additional space (beyond the input vectors).