Wednesday, August 09, 2006

Math Tip: Find the Angle Between Two Vectors

I almost always forget how to do this and need to rederive it every time I need it, I'm posting the algorithm here.

Assume two unit-length vectors A and B. The dot product of the two gives us the cosine of the angle between them.

cos θ = A·B.

Of course, that's the easy part to remember and, of course, everyone forgets that

cos-1(cos θ) ≠ θ,

but rather

cos-1(cos θ) = ±θ.

So, how to properly determine if it is +θ or -θ? The answer is to also check the sign of the cosine of the angle between A and C, the vector that is B rotated by π/2. Then, if the signs do not agree (i.e. A·B < 0 and A·C > 0 or, A·B > 0 and A·C < 0), θ needs to be negated.


  1. Unless I am mistaken, I don't think this is entirely correct and depends on whether the angle is greater or less than 90 degrees.

    If the angle is less than 90 degrees and the two dot products agree with each other in sign, than you must negate the angle. If the angle is greater than 90 degrees and the dot products disagree in sign, you must also negate the angle.

    I could be wrong but I tried drawing out the quadrants and all seemed well. Regards.

  2. A dot B returns [0, pi], never a negative value!