Angle difference between two bearings

From Rosetta Code
Revision as of 02:01, 16 December 2016 by rosettacode>TimSC (Created page with "Category:Geometry {{draft task}} Finding the angle between two bearings is often confusing.<ref>[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-be...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Angle difference between two bearings is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Finding the angle between two bearings is often confusing.[1]

Task

We need to find the angle which is the result of the subtraction b2-b1, where b1 and b2 are both bearings. The result must be expressed in the range +180 to -180 degrees. Compute the angle for the following pairs:

  • 20 degrees (b1) and 45 degrees (b2)
  • -45 and 45
  • -85 and 90
  • -95 and 90
  • -45 and 125
  • -45 and 145

JavaScript

<lang javascript>var deg2rad = 3.14159265/180.0; var rad2deg = 180.0/3.14159265;

function relativeBearing(b1Rad, b2Rad) { b1y = Math.cos(b1Rad); b1x = Math.sin(b1Rad); b2y = Math.cos(b2Rad); b2x = Math.sin(b2Rad); crossp = b1y * b2x - b2y * b1x; dotp = b1x * b2x + b1y * b2y; if(crossp > 0.) return Math.acos(dotp); return -Math.acos(dotp); }

function test() { var deg2rad = 3.14159265/180.0; var rad2deg = 180.0/3.14159265; return relativeBearing(20.0*deg2rad, 45.0*deg2rad)*rad2deg+"\n" +relativeBearing(-45.0*deg2rad, 45.0*deg2rad)*rad2deg+"\n" +relativeBearing(-85.0*deg2rad, 90.0*deg2rad)*rad2deg+"\n" +relativeBearing(-95.0*deg2rad, 90.0*deg2rad)*rad2deg+"\n" +relativeBearing(-45.0*deg2rad, 125.0*deg2rad)*rad2deg+"\n" +relativeBearing(-45.0*deg2rad, 145.0*deg2rad)*rad2deg+"\n"; }</lang>

Output:
25.000000000000004
90
174.99999999999997
-175.00000041135993
170.00000000000003
-170.00000041135996

References