2

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;
}
Bilesh Ganguly
  • 3,000
  • 2
  • 31
  • 50
Lolslayer
  • 43
  • 8

2 Answers2

0

This is just do

package angle;

public class Example {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(distance(-179,180));
}

private static double distance(double alpha, double beta) {
    if(beta>=0 && alpha >=0 && beta<=180 && alpha<=180){
        double phi = (beta - alpha) % 360;       // This is either the distance or 360 - distance
        double distance = phi > 180 ? 360 - phi : phi;
        return distance;
    }else if(beta<0 || alpha < 0){
        double phi = (beta - alpha) % 360;       // This is either the distance or 360 - distance
        double distance = phi;
        return distance;
    }
    return 0;
}
}

prints 359.0 you can reduce it to 360-distance to get smallest distance

replacing with double distance = phi > 180 ? 360 - phi : phi;

Also Refer to

How do I calculate the difference of two angle measures?

Community
  • 1
  • 1
prem30488
  • 2,749
  • 2
  • 19
  • 53
0

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
Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199
  • Rakesh already helped me, but this does excactly the same so if people visit this topic, this is the way to go – Lolslayer May 19 '16 at 11:42