I looked at some solutions here but none provide what I need, so:
I need to average an array of angles(0 to 359.9, no negatives) (A1 + A2 + A3 + An) / n
The
A ray leaving a circle can be represented in more than one manner. It could be 0 degrees, 360 degrees, 720 degrees, etc. You need to determine what is the correct acceptable answer for you case, and covert intermediate answers to the final answer before presenting it.
1 + 359 + 2 + 358 = 360 + 360 = 720 degrees in total
720 / 4 = 360 / 2 = 180 degrees on average
It's not that the answer should be zero, it's that 359 degrees is not equivalent to -1 degrees because the angle goes around the circle "the other way".
Do you want to round it off i.e. 0 should come after 359 degree?
take a modulus of the result with 360.
avg = ( (a1 + a2 + an) /n ) % 360
Add unit vectors of each angle, and convert the resulting vector back into an angle. If the result vector is of zero length, the inputs cancelled each other out and the result is indeterminate.
A unit vector has a length of 1, and its x and y lengths are given by the cosine and sine of the angle. Thus you average your examples as in the following pseudo-code:
x = cos(radians(1)) + cos(radians(359)) + cos(radians(2)) + cos(radians(358));
y = sin(radians(1)) + sin(radians(359)) + sin(radians(2)) + sin(radians(358));
angle = degrees(atan2(y, x));
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.
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:
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.