Find the Angle between two Bearings

12,094

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

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'
  }
}

Solution 5

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;
Share:
12,094
Adam Davies
Author by

Adam Davies

Updated on June 03, 2022

Comments

  • Adam Davies
    Adam Davies about 2 years

    Given two bearing, how do I find the smallest angle between them?

    So for example if 1 heading is 340 degrees and the second is 10 degrees the smallest angle will be 30 degrees.

    I've attached a picture to show what I mean. I've tried subtracting one from the other but that didn't work because of the wrap around effect of a circle. I've also tried using negative degrees (180 - 359 being -180 to 0) but that got messed up when trying to calculate the angle between positive and negative number.

    I'm sure there must be an easier way that having lots of if statements.

    Thank for your help. Adam

    BTW. This is a navigation question so the radius of the circle is unknown.

    Finding the angle between two headings