Passed
Push — master ( 4b5d57...3ba359 )
by Arkadiusz
02:42
created

StandardDeviation::sumOfSquares()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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