Average wind direction

Here’s a little PHP snippet for averaging wind directions.
Turns out there is a reason they teach you math in school 😉compass

//Expects: An array containing wind direction in degrees
//Returns: Average wind direction

function avgWind($directionArray) {
  $sinsum = 0; $cossum = 0;
  foreach ($directionArray as $value) {
    $sinsum += sin(deg2rad($value));
    $cossum += cos(deg2rad($value));
  }
  return ((rad2deg(atan2($sinsum, $cossum)) + 360) % 360);
}

Some of you might have noticed that this only makes sense if you collect your samples multiple times per minute. This implementation also doesn’t take wind speed into consideration. If this is your intent, multiply the sin(..) and cos(..) in the loop with the wind speed at that time. And yes, averaging [0,180] will result in 90° although 270° would also be correct, hence my first remark.