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

StandardDeviation   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 6
c 2
b 0
f 1
lcom 0
cbo 2
dl 0
loc 36
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B population() 0 25 6
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