Vector Angles: From Dot Product to Degrees

3D GeometryMedium+15 XP+15

Vector Angles: From Dot Product to Degrees

Two vectors point somewhere in space. How far apart are their directions, in degrees?

The dot product already knows, you just have to unwrap it. Divide by both lengths to get the cosine of the angle, then undo the cosine:

cos⁡θ=a⋅b∥a∥ ∥b∥,θ=arccos⁡(cos⁡θ)\cos\theta = \frac{a \cdot b}{\|a\| \, \|b\|}, \qquad \theta = \arccos(\cos\theta)cosθ=∥a∥∥b∥a⋅b​,θ=arccos(cosθ)

Task: write angle_degrees(a, b) returning the angle in degrees, rounded to 4 decimal places.

  • a and b are vectors of the same length (3D in the tests, but the arithmetic doesn't care), and neither is all zeros.
  • math.acos works in radians, so convert at the end with math.degrees.
  • Clamp the cosine into [-1, 1] before calling acos. Floating-point arithmetic can produce 1.0000000000000002 for two identical vectors, and acos raises a ValueError on anything past 1. One max(-1.0, min(1.0, c)) prevents it.
  • The answer always lands between 0 and 180 degrees. arccos can't tell you which way around the angle goes, and in 3D there's no single sensible answer to that anyway.

The three landmarks worth knowing by heart: same direction is 0°, perpendicular is 90°, and opposite is 180°. Dividing by the lengths is what makes this about direction alone — a vector and its own double give an angle of exactly zero.

Examples

a = [1, 0, 0]
b = [0, 1, 0]
returns 90.0
a = [1, 1, 0]
b = [1, 0, 0]
returns 45.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run