Reputation: 7
Given that I have two true bearings as a start bearing 315 degrees and an end bearing 45 degrees, is there a better way to determine the angle between the two true bearings? The complication comes in when the start bearing is greater than the end bearing. I have the following that works but I figure there is a better/mathematical way.
double tStartBearing = 315;
double tEndBearing = 45;
double tAngle;
if (tStartBearing > tEndBearing) {
tAngle = tStartBearing - tEndBearing - 180;
} else {
tAngle = tEndBearing - tStartBearing;
}
Expect the resulting value of tAngle to be 90. Consider a start bearing of 0 and an end bearing of 359.9, the resulting value of tAngle should be 359.9, not 0.1.
Upvotes: 0
Views: 326
Reputation: 17668
The (signed) angle is always end - start
. Assuming the start and end angles are both in the same range [n, n + 360)
, their difference will be between (-360, 360)
.
To normalize the difference to a positive angle in the range [0, 360)
, use:
tAngle = (tEndBearing - tStartBearing + 360) % 360;
To normalize the difference to a signed angle in the range [-180, 180)
, instead, use:
tAngle = (tEndBearing - tStartBearing + 360 + 180) % 360 - 180;
The above work whether the start angle is smaller than the end one, or the other way around.
Upvotes: 2