Skip to content

Instantly share code, notes, and snippets.

@fatihgune
Last active December 6, 2020 16:14
Show Gist options
  • Select an option

  • Save fatihgune/0e4b6103145ecdecf790ad5ecab88ac2 to your computer and use it in GitHub Desktop.

Select an option

Save fatihgune/0e4b6103145ecdecf790ad5ecab88ac2 to your computer and use it in GitHub Desktop.
Calculate Standard Deviation (Sample)
<?
/**
* @param array $a
* @param bool $sample
* @return false|float
*/
public function calculateStandardDeviationSample(array $a, $sample = true)
{
$n = count($a);
if ($n === 0) {
trigger_error("The array has zero elements", E_USER_WARNING);
return false;
}
if ($sample && $n === 1) {
trigger_error("The array has only 1 element", E_USER_WARNING);
return false;
}
$mean = array_sum($a) / $n;
$carry = 0.0;
foreach ($a as $val) {
$d = ((double)$val) - $mean;
$carry += $d * $d;
}
if ($sample) {
--$n;
}
return sqrt($carry / $n);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment