Find the Angle between two Bearings

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 07:19:49
float getDifference(float a1, float a2) {
    return Math.min((a1-a2)<0?a1-a2+360:a1-a2, (a2-a1)<0?a2-a1+360:a2-a1)
}

I ended up using the following formula found on this message board because I needed the result to be signed based on the direction (clockwise or counterclockwise). It has a good explanation of exactly what's going on.

((((bearing - heading) % 360) + 540) % 360) - 180

What about:

angle = Math.abs(a1-a2);
if (angle > 180)
    angle = 360 - angle;

You mention an issue regarding positive and negative numbers, so perhaps there is something I'm not considering here...

If angle direction is needed, then this will work:

    int maxBearing = Math.max(bearing0, bearing1);
    int minBearing = Math.min(bearing0, bearing1);
    int firstDir = maxBearing - minBearing;  
    int secondDir = minBearing + 360 - maxBearing;  
    int diff = Math.min(firstDir, secondDir);

    boolean anticlock_dir = false;

    int anticlock = bearing1 + diff;
    if (anticlock >= 360)
        anticlock = anticlock - 360;

    if (anticlock ==  bearing0)
        anticlock_dir = true;

For navigation, you might want to know if b1 is left or right of b2, so here it is in a nice function. (Assumes exactly 0 is not a use case)

function isBearing1LeftOrRightOfBearing2 (b1, b2) {
  if (Math.sign(((b1 - b2 + 540) % 360) - 180) > 0) {
    return 'left'
  } else {
    return 'right'
  }
}

You need to consider the difference in both directions.

public static double bearingDiff(double a, double b) {
    double maxBearing = Math.max(a, b);
    double minBearing = Math.min(a, b);
    double antiClockwiseDiff = maxBearing - minBearing;
    double clockwiseDiff = minBearing + 360 - maxBearing;
    return Math.min(antiClockwiseDiff, clockwiseDiff);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!