Home > Uncategorized > How to calculate the average angle of bearings

How to calculate the average angle of bearings

August 26th, 2010 Ed Leave a comment Go to comments

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;
Categories: Uncategorized Tags:
  1. Geoff
    November 25th, 2011 at 09:45 | #1

    Hi,

    This is an interesting post. Note that:
    sin(angle) / cos (angle) = tan(angle)
    so you are doing:
    atan2( tan(angle) )
    I assume the angle is the addition of the two bearings, so
    angle = 355 + 5 = 360.

    In a calculator, if you did atan(tan(360deg)) you would get 0 deg also. That just relies on the periodic nature of tan (http://www.mathsrevision.net/gcse/pages.php?page=39).

    I don’t really see how that amounts to treating the angles/bearings as vectors? I’m not sure also why you use atan2 rather than atan, but I would be interested to hear why if you can remember.

    Cheers

  2. Ed
    November 25th, 2011 at 11:55 | #2

    Hi,

    To be honest, I did what seemed to work after talking to several mathematical people, so I’m sure there are better ways to get it to work.

    I thought it was vector-like, given you can imagine it as moving a radius around a circle, looking at the horizontal and vertical displacement.

    Sorry this doesn’t clarify anything!!!

  1. No trackbacks yet.