Created
October 24, 2023 03:03
-
-
Save szepeviktor/ec520182f47ce1f28f4cfffb61b03d83 to your computer and use it in GitHub Desktop.
Calculate standard deviation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} |
Author
szepeviktor
commented
Oct 24, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment