Issue
I know a way to find the angle difference of two angles between [0,180], but I'm trying to find out a way to find the angle difference of two angles between [-179,180].
My code is as follows; it doesn't work properly:
private int distance2(int alpha, int beta) {
int phi = beta - alpha;// % 360; // This is either the distance or 360 - distance
int distance = 0;
if (phi < -360) {
distance = 360 + phi;
} // end of if
else{
distance = phi;
}
return distance;
}
Solution
If you are sure that alpha and beta are both in [-180, 180] interval, you know
-360 <= alpha - beta <= 360
So you can use:
private int distance2(int alpha, int beta) {
int distance = beta - alpha; // This is the distance mod 360
if (phi <= -180) {
distance += 360; // you were between -360 and -180 -> 0 <= distance <= 180
else if (phi > 180) {
distance -= 360; // you were between 180 and 360 -> 180 < distance <= 0
}
return distance;
}
If you cannot be sure of input values, just replace first line with:
int distance = (beta - alpha) % 360; // forces distance in ]-360, 360[ range
Answered By - Serge Ballesta
Answer Checked By - Cary Denson (JavaFixing Admin)