Skip to content

angle_btw

Angle between two \(n\)-dimensional vectors.

a = angle_btw(v1, v2)

Typically, the angle between two vectors v1 and v2 can be obtained with:

acos(dot(v1, v2) / (norm(v1) * norm(v2)))

However, this approach is numerically unstable. The version provided here is numerically stable and based on the AngleBetweenVectors Julia package by Jeffrey Sarnoff (MIT license), implementing an algorithm provided by Prof. W. Kahan in these notes (see page 15).

Arguments

  • v1 - First vector.
  • v2 - Second vector.

Return values

  • a- Angle between v1 and v2 in radians.

Examples

v1 = [1.0, 1.0, 1.0, 1.0];
v2 = [1.0, 0.0, 0.0, 0.0];
rad2deg(angle_btw(v1, v2)) % Should be 60 degrees
% ans = 60.000