php-ml/src/Phpml/Math/Statistic/StandardDeviation.php

45 lines
874 B
PHP
Raw Normal View History

<?php
2016-04-27 21:28:01 +00:00
declare (strict_types = 1);
namespace Phpml\Math\Statistic;
use Phpml\Exception\InvalidArgumentException;
class StandardDeviation
{
/**
* @param array|float[] $a
2016-04-27 21:28:01 +00:00
* @param bool $sample
*
* @return float
*
* @throws InvalidArgumentException
*/
public static function population(array $a, $sample = true)
{
2016-04-27 21:28:01 +00:00
if (empty($a)) {
throw InvalidArgumentException::arrayCantBeEmpty();
}
2016-04-27 21:28:01 +00:00
$n = count($a);
if ($sample && $n === 1) {
throw InvalidArgumentException::arraySizeToSmall(2);
}
2016-04-27 21:28:01 +00:00
2016-04-27 21:57:05 +00:00
$mean = Mean::arithmetic($a);
$carry = 0.0;
foreach ($a as $val) {
$d = $val - $mean;
$carry += $d * $d;
};
2016-04-27 21:28:01 +00:00
if ($sample) {
--$n;
}
return sqrt((float)($carry / $n));
}
}