2016-04-27 21:04:59 +00:00
|
|
|
<?php
|
2016-04-27 21:28:01 +00:00
|
|
|
|
2016-11-20 21:53:17 +00:00
|
|
|
declare(strict_types=1);
|
2016-04-27 21:04:59 +00:00
|
|
|
|
|
|
|
namespace Phpml\Math\Statistic;
|
|
|
|
|
|
|
|
use Phpml\Exception\InvalidArgumentException;
|
|
|
|
|
|
|
|
class StandardDeviation
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @param array|float[] $a
|
|
|
|
*
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
2017-11-22 21:16:10 +00:00
|
|
|
public static function population(array $a, bool $sample = true): float
|
2016-04-27 21:04:59 +00:00
|
|
|
{
|
2016-04-27 21:28:01 +00:00
|
|
|
if (empty($a)) {
|
2016-04-27 21:04:59 +00:00
|
|
|
throw InvalidArgumentException::arrayCantBeEmpty();
|
|
|
|
}
|
2016-04-27 21:28:01 +00:00
|
|
|
|
2016-04-27 21:04:59 +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);
|
2016-04-27 21:04:59 +00:00
|
|
|
$carry = 0.0;
|
|
|
|
foreach ($a as $val) {
|
|
|
|
$d = $val - $mean;
|
|
|
|
$carry += $d * $d;
|
2016-11-20 21:53:17 +00:00
|
|
|
}
|
2016-04-27 21:04:59 +00:00
|
|
|
|
2016-04-27 21:28:01 +00:00
|
|
|
if ($sample) {
|
2016-04-27 21:04:59 +00:00
|
|
|
--$n;
|
|
|
|
}
|
|
|
|
|
2016-05-02 21:36:58 +00:00
|
|
|
return sqrt((float) ($carry / $n));
|
2016-04-27 21:04:59 +00:00
|
|
|
}
|
|
|
|
}
|