tags:

views:

439

answers:

3

Given 2 angles in the range -PI -> PI around a coordinate, what is the value of the smallest of the 2 angles between them?

Taking into account that the difference between PI and -PI is not 2 PI but zero

+4  A: 

If your two angles are x and y, then one of the angles between them is abs(x - y). The other angle is (2 * PI) - abs(x - y). So the value of the smallest of the 2 angles is:

min((2 * PI) - abs(x - y), abs(x - y))
Laurence Gonsalves
beat me by 1 second! :) cheers
Donnie DeBoer
^_^ thanks, but I challenge you to give me a version that preserves the negative positiveness, aka 40* to the left versus 40* to the right
Tom J Nowell
+1  A: 

x is the target angle. y is the source or starting angle:

atan2(sin(x-y), cos(x-y))

It returns the signed delta angle. Note that depending on your API the order of the parameters for the atan2() function might be different.

Peter B
+1  A: 

I rise to the challenge of providing the signed answer:

def f(x,y):
  import math
  return min(y-x, y-x+2*math.pi, y-x-2*math.pi, key=abs)
David Jones
Ah... the answer is a Python function by the way. Sorry, I was in Python mode for a moment. Hope that's okay.
David Jones
I shall plug the new formula into my code upstairs and see what becomes of it! ( thankyou ^_^ )
Tom J Nowell
I'm pretty sure PeterB's answer is correct too. And evilly hackish. :)
David Jones
But this one contains no trig functions :)
nornagon