Find the angle between the two bearings

Given the two bearings, 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 attached a photo to show what I mean. I tried to subtract one from the other, but this did not work because of the wrapper around the circle effect. I also tried using negative degrees (180-359 - from -180 to 0), but this was messed up when trying to calculate the angle between a positive and negative number.

I am sure there should be an easier way to have many if .

Thank you for your help. Adam

BTW. This is a navigation issue, so the circle radius is unknown.

Finding the angle between two headings

+7
source share
6 answers
 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) } 
+6
source

In the end, I got the following formula found on this bulletin board , because I needed a result that should be signed depending on the direction (clockwise or counterclockwise). This is a good explanation of what is happening.

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

What about:

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

You mentioned a problem regarding positive and negative numbers, so maybe there is something that I am not considering here ...

+5
source

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); } 
0
source

If angle direction is required, 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; 
0
source

For navigation, you can find out if b1 is left or right of b2, so this is a nice feature here. (It is assumed that 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' } } 
0
source

All Articles