Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Created October 24, 2023 03:03
Show Gist options
  • Save szepeviktor/ec520182f47ce1f28f4cfffb61b03d83 to your computer and use it in GitHub Desktop.
Save szepeviktor/ec520182f47ce1f28f4cfffb61b03d83 to your computer and use it in GitHub Desktop.
Calculate standard deviation
<?php
/**
* Calculate standard deviation
*
* Square root of sum of squares divided by N-1
*
* @param list<float> $values
*/
function sd(array $values): float
{
$noOfValues = count($values);
$sum = array_sum(
array_map(
static function (float $x, float $mean): float {
return pow($x - $mean, 2);
},
$values,
array_fill(0, $noOfValues, array_sum($values) / $noOfValues)
)
);
return sqrt($sum / ($noOfValues - 1));
}
@szepeviktor
Copy link
Author

echo sd([67, 89, 93, 102, 84]), "\n";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment