Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wasn't sure if this was a better place than Stack Overflow to ask this question. On a basic level, I have an algorithm I've written in Java to compute a number, but I feel like there's a better way to write it without a loop that just involves use of floor and things like that.

So here's my algorithm:

float startAngle = getRotation();
double dAngle = (startAngle < 0 ? -Math.PI : Math.PI);
double endAngle = (float)((destination % 2 == 0) ? 0 : dAngle/2);
while (Math.abs(endAngle - startAngle) > Math.PI/2)
  endAngle += dAngle;

In simpler terms it does the following:

  1. Get the current angle of the object
  2. Get a delta angle based on whether the object has been rotated left or right (further left or further right)
  3. Define an angle to rotate the object to, based on whether the destination should be rotated parallel or perpendicular to 0
  4. As long as the difference between the end angle and start angle is greater than 90 degrees, change the end angle by the delta from step 2.

The reason behind all this is I've got playing cards on the screen at random angles, which any of four players can take (where destination 0 is the bottom of the screen, 1 is left, 2 is top, and 3 is right). I want to rotate the playing cards the shortest distance to face that player as they take them. This algorithm works correctly, but like I said before, it seems like there should be a way to do this without a loop. Is there?

share|cite|improve this question

Once you have an angle you want to rotate, you are trying to reduce it to the range $(-\pi,\pi)$. I don't know if Java will do modulo on reals, nor what it returns if you do a%$\pi$ for $a \lt 0$. It looks like dAngle is in the range $(-2\pi,2\pi)$ in which case you can do it with if statements:

if dAngle < -PI: dAngle +=2PI

elseif dAngle > PI: dAngle-=2PI


share|cite|improve this answer
Handily, modulus works like you'd want it to. That is, -pi - 1 mod pi = -1. However, I'm not necessarily reducing to that range. If the card has been rotated 5.2*pi radians, I want to find the nearest angle parallel or perpendicular to 0, 5 or 6 pi. – Ed Marty May 21 '11 at 12:20
If you include parallel or perpendicular, you can do mod $\pi/2$. I hadn't gotten that from the original description. – Ross Millikan May 21 '11 at 15:14
Well, this is depending on what the destination is. If the destination is player 1 or 3, then it must be perpendicular. If player 0 or 2, then it must be parallel. – Ed Marty May 22 '11 at 19:06

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.