A wind vane on a hill reports the wind direction every minute as a compass heading in degrees: 0 is north, 90 east, 180 south, 270 west, and headings wrap round, so 359 is right next to 0. The farmer wants the average direction over a period.
Adding up the numbers and dividing does not work: headings 350 and 10 are both just off north, but their plain mean is 180, due south. Instead, treat each heading as an arrow of length 1 pointing that way, with components east = sin(heading) and north = cos(heading). Average the arrows position by position. The direction of the mean arrow is the average heading, and its length (between 0 and 1) says how consistent the wind was: 1 if every reading was the same, near 0 if the wind came from everywhere.
Write average_heading(degrees) that returns a tuple (heading, steadiness):
headingis the compass direction of the mean arrow in degrees, rounded to 2 decimals, between0and360(report360.0as0.0),steadinessis the length of the mean arrow, not rounded.
If the length of the mean arrow is below 1e-9 the readings cancel out and there is no average direction: return None.
Examples
Input: degrees = [350, 10]
Output: (0.0, 0.984807753012208)
Input: degrees = [90, 180]
Output: (135.0, 0.7071067811865476)
Explanation: the arrows [1, 0] (east) and [0, -1] (south) average to [0.5, -0.5], which points
south-east and has length 0.707.
Input: degrees = [0, 120, 240]
Output: None
Constraints
1 <= len(degrees) <= 10**4; every heading is an int or float with0 <= heading < 360math.sinandmath.costake radians (math.radiansconverts);math.atan2(east, north)gives the angle of an arrow measured from north towards east, in radians between-piandpi
Goals
- Turn an angle into a unit vector and back
- Average directions by averaging vectors instead of numbers
- Use the length of the mean vector to measure how consistent the directions are