StandardDeviation::population()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 22
rs 9.2222
c 0
b 0
f 0
cc 6
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 float[]|int[] $numbers
13
     */
14
    public static function population(array $numbers, bool $sample = true): float
15
    {
16
        $n = count($numbers);
17
        if ($n === 0) {
18
            throw new InvalidArgumentException('The array has zero elements');
19
        }
20
21
        if ($sample && $n === 1) {
22
            throw new InvalidArgumentException('The array must have at least 2 elements');
23
        }
24
25
        $mean = Mean::arithmetic($numbers);
26
        $carry = 0.0;
27
        foreach ($numbers as $val) {
28
            $carry += ($val - $mean) ** 2;
29
        }
30
31
        if ($sample) {
32
            --$n;
33
        }
34
35
        return ($carry / $n) ** .5;
36
    }
37
38
    /**
39
     * Sum of squares deviations
40
     * ∑⟮xᵢ - μ⟯²
41
     *
42
     * @param float[]|int[] $numbers
43
     */
44
    public static function sumOfSquares(array $numbers): float
45
    {
46
        if (count($numbers) === 0) {
47
            throw new InvalidArgumentException('The array has zero elements');
48
        }
49
50
        $mean = Mean::arithmetic($numbers);
51
52
        return array_sum(array_map(
53
            static function ($val) use ($mean): float {
54
                return ($val - $mean) ** 2;
55
            },
56
            $numbers
57
        ));
58
    }
59
}
60