Completed
Push — develop ( af3b57...b5e4cb )
by Arkadiusz
02:26
created

StandardDeviation::population()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 25
rs 8.439
cc 6
eloc 14
nc 6
nop 2
1
<?php
2
3
declare (strict_types = 1);
4
5
namespace Phpml\Math\Statistic;
6
7
use Phpml\Exception\InvalidArgumentException;
8
9
class StandardDeviation
10
{
11
    /**
12
     * @param array|float[] $a
13
     * @param bool          $sample
14
     *
15
     * @return float
16
     *
17
     * @throws InvalidArgumentException
18
     */
19
    public static function population(array $a, $sample = true)
20
    {
21
        if (empty($a)) {
22
            throw InvalidArgumentException::arrayCantBeEmpty();
23
        }
24
25
        $n = count($a);
26
27
        if ($sample && $n === 1) {
28
            throw InvalidArgumentException::arraySizeToSmall(2);
29
        }
30
31
        $mean = Mean::arithmetic($a);
32
        $carry = 0.0;
33
        foreach ($a as $val) {
34
            $d = $val - $mean;
35
            $carry += $d * $d;
36
        };
37
38
        if ($sample) {
39
            --$n;
40
        }
41
42
        return sqrt($carry / $n);
43
    }
44
}
45