Averages/Mean angle

From Rosetta Code
Revision as of 23:16, 9 July 2012 by rosettacode>Paddy3118 (New draft task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Averages/Mean angle is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.

If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then just using the Pythagorean average of the numbers yields an answer of 180 degrees, whereas if you can note that 350 degrees is equivalent to 10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.

To calculate the mean angle of several angles:

  1. Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
  2. Compute the Pythagorean mean of the complex numbers.
  3. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.

You can alternatively use this formula:

Given the angles the mean is computed by

The task is to:

  1. write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. (You should use a built-in function if you have one that does this for degrees or radians).
  2. Use the function to compute the means of these lists of angles (in degrees): [350, 10], [90, 180, 270, 360], [10, 20, 30]; and show your output here.

Python

<lang python>>>> from cmath import rect, polar, phase >>> from math import radians, degrees >>> def mean_angle(deg): ... return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg))) ... >>> for angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]: ... print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees') ... The mean angle of [350, 10] is: -0.0 degrees The mean angle of [90, 180, 270, 360] is: -90.0 degrees The mean angle of [10, 20, 30] is: 20.0 degrees >>> </lang>