Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm or formula for the shortest direction of travel between two degrees on a circle?

Given two degrees on a 360 degree circle. Lets call them Source and Destination.

For example Source could be 120 degrees and Destination could be 30 degrees.

Is there an elegant solution to the question of which direction of travel from Source to Destination is shorter, i.e. is it shorter clockwise (increasing the degrees) or anti clockwise (decreasing the degrees)?

For example with the degrees given above then the solution would be: Go anti clockwise. On the other hand with Source as 350 and Destination as 20 then the solution would be: Go clockwise.

like image 488
Karlth Avatar asked Sep 15 '11 09:09

Karlth


1 Answers

if ((dest - source + 360) % 360 < 180)
  // clockwise
else
  // anti-clockwise

BTW, your convention that clockwise == "increasing the degrees" is the opposite of the Trigonometry 101 convention that the rest of the world is using, and is therefore confusing (was to me, anyhow).

like image 70
NPE Avatar answered Sep 23 '22 02:09

NPE