Skip to content

Instantly share code, notes, and snippets.

@carloscabo
Last active July 27, 2019 17:16
Show Gist options
  • Select an option

  • Save carloscabo/96e70853f1bb6b6a4d33e4c5c90c6cbb to your computer and use it in GitHub Desktop.

Select an option

Save carloscabo/96e70853f1bb6b6a4d33e4c5c90c6cbb to your computer and use it in GitHub Desktop.
Calculate the mean / average of a set of angles in radians / degrees
<?php
/*
From: https://en.wikipedia.org/wiki/Mean_of_circular_quantities
Parameters:
$angles: array
$degrees: boolean. Angles and result in degrees (default)
*/
function mean_of_angles( $angles, $degrees = true ) {
if ( $degrees ) {
$angles = array_map("deg2rad", $angles); // Convert to radians
}
$s_ = 0;
$c_ = 0;
$len = count( $angles );
for ($i = 0; $i < $len; $i++) {
$s_ += sin( $angles[$i] );
$c_ += cos( $angles[$i] );
}
// $s_ /= $len;
// $c_ /= $len;
$mean = atan2( $s_, $c_ );
if ( $degrees ) {
$mean = rad2deg( $mean ); // Convert to degrees
}
return $mean;
}
/* Usage */
$angles = [ 355, 5, 15 ];
echo mean_of_angles( $angles ); // Returns 5
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment