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

Correlation   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 3
c 2
b 0
f 0
lcom 0
cbo 2
dl 0
loc 37
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B pearson() 0 26 3
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