Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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 int[]|float[] $x
13
     * @param int[]|float[] $y
14
     *
15
     * @throws InvalidArgumentException
16
     */
17
    public static function pearson(array $x, array $y): float
18
    {
19
        if (count($x) !== count($y)) {
20
            throw new InvalidArgumentException('Size of given arrays does not match');
21
        }
22
 
23
        $count = count($x);
24
        $meanX = Mean::arithmetic($x);
25
        $meanY = Mean::arithmetic($y);
26
 
27
        $axb = 0;
28
        $a2 = 0;
29
        $b2 = 0;
30
 
31
        for ($i = 0; $i < $count; ++$i) {
32
            $a = $x[$i] - $meanX;
33
            $b = $y[$i] - $meanY;
34
            $axb += ($a * $b);
35
            $a2 += $a ** 2;
36
            $b2 += $b ** 2;
37
        }
38
 
39
        return $axb / ($a2 * $b2) ** .5;
40
    }
41
}