How to calculate the average angle of bearings
This is going to be a tediously dull post, but given the amount of faffing I did, I don’t want to forget it!
Firstly, this is mostly not my maths – this is thanks to @helenbowyer, @bluerhinos and a parent of a scout who saw a link to my site on @rmappleby’s blog and then saw my tweet asking for help!
The problem is what happens when you cross the 0/360 boundary – how to average 5 degrees and 355 degrees to get 0 degrees. A “mean” would give 180 degrees – oops!
The answer is trigonometry, treating the angles as vectors.
First get the SIN of the angle, and divide by the COS of it. Then take the “ATAN2″ of it to get the final result. Tada!
For my application, I am putting the last 40 values into an ArrayList and calculating a weighted average (in Utilities.weightedAverage()) – you can replace this with any averaging function. Here’s the Java:
sinTotals.add(Math.sin(angleInRadians));
cosTotals.add(Math.cos(angleInRadians));
if (sinTotals.size() > 40) {
sinTotals.remove(0);
cosTotals.remove(0);
}
double sinAverage = Utilities.weightedAverage(sinTotals);
double cosAverage = Utilities.weightedAverage(cosTotals);
double direction =
(Math.toDegrees(Math.atan2(sinAverage, cosAverage)) + 360) % 360;