Averaging degrees is a little trickier than it sounds.
I had to do this at work the other day and want to share my findings.
- Adding 360 to any of your values should not change your average.
e.g. avg(2 4 18) = avg(362,4,18) = 8
- Shifting all values by a constant value should shift the average equally much.
e.g. avg(2-3,4-3,18-3) = avg(359,1,15) = 8-3
- If your degrees "cancel out", e.g. 0,120,240, the average is undefined
(i.e. there are several equally good answers).
I see no way to deal with this other than giving an error message.
After falling into several traps, I ended up with the following definition:
Average is the value which minimizes the variance.
Once given the average, variance can be computed by:
- Shifting all values by the same angle such that the average is at 180.
(This is equivalent to "cutting" the circle at the opposite side of the average.)
- Normalizing all the angles to be between 0 and 360.
- Computing the normal average.
- Shifting the average back by the angle you shifted the values before (reversing step 1).
This takes O(n^2) time.
However, if all your values lie within a span of 180 degree, you can shift the values such that 0 is contained in the biggest value gap and then compute the normal average.
This takes O(n) time.