Last active
December 6, 2020 16:14
-
-
Save fatihgune/0e4b6103145ecdecf790ad5ecab88ac2 to your computer and use it in GitHub Desktop.
Calculate Standard Deviation (Sample)
This file contains hidden or 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
| <? | |
| /** | |
| * @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