开发者

How do I calculate the difference of two angle measures? [duplicate]

This question already has answers here: How can I find the smallest difference between two angles around a point? (10 answers) 开发者_开发百科 Closed 6 years ago.

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°


    /**
     * 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;
    }


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.


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


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).


How about the following:

dist = (a - b + 360) % 360;
if (dist > 180) dist = 360 - dist;


diff = MAX(angle1, angle2) - MIN(angle1, angle2);  
if (diff > 180) diff = 360 - diff;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜