23

How can I calculate the difference of two angle measures (given in degrees) in Java so the result is in the range [0°, 180°]?

For example:

350° to 15° = 25°
250° to 190° = 60°
andand
  • 15,638
  • 9
  • 48
  • 76
NullPointerException
  • 32,153
  • 66
  • 194
  • 346
  • 1
    If you're calculating distance, why is the result in degrees? – Buhake Sindi Sep 27 '11 at 14:29
  • Can you clarify - are you looking for something built in or are you just asking for a method? also should it take direction into account? Your first example is 25 degrees clockwise and your second is 60 degrees anticlockwise. If you just want the shortest distance then your results should be 0 to 180 (or -180 to 180 if you want to show direction). – Chris Sep 27 '11 at 14:31
  • Btw you should not allow 360 because 360 = 0. The domain of the entry arguments should be [0, 360). – m0skit0 Sep 27 '11 at 14:33
  • Edited for clarity; feel free to roll back if this isn't what you really wanted. – andand Sep 27 '11 at 15:04

6 Answers6

54
    /**
     * Shortest distance (angular) between two angles.
     * It will be in range [0, 180].
     */
    public static int distance(int alpha, int beta) {
        int phi = Math.abs(beta - alpha) % 360;       // This is either the distance or 360 - distance
        int distance = phi > 180 ? 360 - phi : phi;
        return distance;
    }
Dmitry Ryadnenko
  • 20,952
  • 4
  • 38
  • 52
  • 8
    and for "Signed difference", append the following code... int sign = (a - b >= 0 && a - b <= 180) || (a - b <= -180 && a- b>= -360) ? 1 : -1; r *= sign; – M. Usman Khan Jun 17 '15 at 09:08
  • This really helped me, thank you. –  Feb 04 '16 at 18:06
22

In addition to Nickes answer, if u want "Signed difference"

int d = Math.abs(a - b) % 360; 
int r = d > 180 ? 360 - d : d;

//calculate sign 
int sign = (a - b >= 0 && a - b <= 180) || (a - b <=-180 && a- b>= -360) ? 1 : -1; 
r *= sign;

EDITED:

Where 'a' and 'b' are two angles to find the difference of.

'd' is difference. 'r' is result / final difference.

M. Usman Khan
  • 4,258
  • 1
  • 48
  • 62
8

Just take the absolute value of their difference, then, if larger than 180, substract 360° and take the absolute value of the result.

JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174
5

Just do

(15 - 350) % 360

If the direction doesn't matter (you want the one that yields the smallest value), then do the reverse subtraction (mod 360) and calculate the smallest value of the two (e.g. with Math.min).

Artefacto
  • 90,634
  • 15
  • 187
  • 215
4

How about the following:

dist = (a - b + 360) % 360;
if (dist > 180) dist = 360 - dist;
NPE
  • 438,426
  • 93
  • 887
  • 970
1
diff = MAX(angle1, angle2) - MIN(angle1, angle2);  
if (diff > 180) diff = 360 - diff;
N3R4ZZuRR0
  • 2,305
  • 3
  • 13
  • 30
Oliver
  • 21,876
  • 32
  • 134
  • 229