StandardDeviation   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 20
dl 0
loc 48
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A population() 0 22 6
A sumOfSquares() 0 13 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