Created
June 23, 2017 08:25
-
-
Save vlastv/d8a57f82f8f8e0eef7370f30b251058c to your computer and use it in GitHub Desktop.
PHP Stats
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 | |
function median(array $elements, $offset = 0, $length = null) | |
{ | |
if ($length === null) { | |
$length = count($elements)-$offset; | |
} | |
sort($elements); | |
$half = $offset + ((int)floor(($length - 1) / 2)); | |
return ($elements[$half] + $elements[$half + 1 - $length % 2]) / 2; | |
} | |
function quartiles(array $elements) | |
{ | |
$length = count($elements); | |
$q2 = median($elements); | |
$q1 = median($elements, 0, floor($length/2)); | |
$q3 = median($elements, ceil($length/2)); | |
return [$q1, $q2, $q3]; | |
} | |
function interquartile_range(array $elements, array $frequencies) { | |
$set = []; | |
foreach($elements as $index => $element) { | |
for($i = 0; $i < $frequencies[$index]; ++$i) { | |
$set[] = $element; | |
} | |
} | |
$q = quartiles($set); | |
return $q[2]-$q[0]; | |
} | |
function mean(array $array) | |
{ | |
return ($n = count($array)) === 0 ? 0 : array_sum($array)/$n; | |
} | |
function standard_deviation(array $array) | |
{ | |
$n = count($array); | |
$mean = mean($array); | |
$carry = 0.0; | |
foreach($array as $value) { | |
$carry += ($value-$mean)**2; | |
} | |
return sqrt($carry / $n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment