Fast way to compare angles.

Started by
4 comments, last by CuppoJava 18 years, 10 months ago
Hey I just realized this today and thought I'd share this trick. If you have a vector A, and you want to see if another vector B is within x degrees of it you can use this trick. Instead of going: float angle1 = arctan A float angle2 = arctan B if( |angle1-angle2| < x) //bla bla You can go: A.normalize B.normalize if( A dot B < cos x) //bla bla Caching the cosine makes the entire operation about twenty times faster. I haven't tried caching the squareroot yet. Without caching, the operation below is still 4 times faster. -Cuppo
Advertisement
wouldn't
if( A dot B < (A.length * B.length * cosx))

be even faster and do the exact same thing?
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
Yea that's the basic idea, except for most of the time you don't know the length of the vector which is why I had the two normalize statements.
-Cuppo
Well since normalization is v / v.length the length ought to either be known or easily computed basicly my method saves you the divisions / multiplications that normalization would give per element.
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
You might be able to skip the square root completely if you square both sides. Of course this introduces the problem that angles that are opposite (cos = -1) will look like right on top of each other, since the sign of the dot product would be lost. Anyway, depending on the situation you might be able to rule out that possibility, or check for the sign of the product (as long as cos x > 0).

That's nice. I didn't think of that.
So once the cosine is cached, this operation will be blazing.
Thx for that tip avaro.
-Cuppo.

This topic is closed to new replies.

Advertisement