Angle difference between two bearings: Difference between revisions

Line 48:
 
=={{header|Javascript}}==
===ES5===
 
This approach should be reliable but it is also very inefficient.
 
Line 83:
170.00000000000003
-170.00000041135996</pre>
 
===ES6===
 
<lang JavaScript>(() => {
const
[Pi, sin, cos, acos] =
['PI', 'sin', 'cos', 'acos']
.map(k => Math[k]),
degRad = x => Pi * x / 180.0,
radDeg = x => 180.0 * x / Pi;
 
 
// relBearing :: Radians -> Radians -> Radians
const relBearing = (ar, br) => {
const
[ax, ay] = [sin(ar), cos(ar)],
[bx, by] = [sin(br), cos(br)],
 
// Cross-product > 0 ?
sign = ((ay * bx) - (by * ax)) > 0 ? +1 : -1;
 
// Sign * dot-product
return sign * acos((ax * bx) + (ay * by));
}
 
// TEST
 
// justifyRight :: Int -> Char -> Text -> Text
const justifyRight = (n, cFiller, strText) =>
n > strText.length ? (
(cFiller.repeat(n) + strText)
.slice(-n)
) : strText;
 
 
// showMap :: Degrees -> Degrees -> String
const showMap = (da, db) =>
justifyRight(6, ' ', `${da}° +`) +
justifyRight(11, ' ',` ${db}° -> `) +
justifyRight(7, ' ', `${(radDeg(relBearing(degRad(da), degRad(db))))
.toPrecision(4)}°`);
 
return [
[20, 45],
[-45, 45],
[-85, 90],
[-95, 90],
[-45, 125],
[-45, 145]
].map(xy => showMap(...xy))
.join('\n');
})();</lang>
 
{{Out}}
<pre>
20° + 45° -> 25.00°
-45° + 45° -> 90.00°
-85° + 90° -> 175.0°
-95° + 90° -> -175.0°
-45° + 125° -> 170.0°
-45° + 145° -> -170.0°</pre>
 
=={{header|Perl 6}}==
9,659

edits