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

Correlation::pearson()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 26
rs 8.8571
cc 3
eloc 17
nc 3
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 Correlation
10
{
11
    /**
12
     * @param array|int[]|float[] $x
13
     * @param array|int[]|float[] $y
14
     *
15
     * @return float
16
     *
17
     * @throws InvalidArgumentException
18
     */
19
    public static function pearson(array $x, array $y)
20
    {
21
        if (count($x) !== count($y)) {
22
            throw InvalidArgumentException::arraySizeNotMatch();
23
        }
24
25
        $count = count($x);
26
        $meanX = Mean::arithmetic($x);
27
        $meanY = Mean::arithmetic($y);
28
29
        $axb = 0;
30
        $a2 = 0;
31
        $b2 = 0;
32
33
        for ($i = 0;$i < $count;++$i) {
34
            $a = $x[$i] - $meanX;
35
            $b = $y[$i] - $meanY;
36
            $axb = $axb + ($a * $b);
37
            $a2 = $a2 + pow($a, 2);
38
            $b2 = $b2 + pow($b, 2);
39
        }
40
41
        $corr = $axb / sqrt($a2 * $b2);
42
43
        return $corr;
44
    }
45
}
46