2016-04-27 21:28:01 +00:00
|
|
|
<?php
|
|
|
|
|
2016-11-20 21:53:17 +00:00
|
|
|
declare(strict_types=1);
|
2016-04-27 21:28:01 +00:00
|
|
|
|
|
|
|
namespace Phpml\Math\Statistic;
|
|
|
|
|
|
|
|
use Phpml\Exception\InvalidArgumentException;
|
|
|
|
|
|
|
|
class Correlation
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @param array|int[]|float[] $x
|
|
|
|
* @param array|int[]|float[] $y
|
|
|
|
*
|
|
|
|
* @return float
|
|
|
|
*
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
|
|
|
public static function pearson(array $x, array $y)
|
|
|
|
{
|
|
|
|
if (count($x) !== count($y)) {
|
|
|
|
throw InvalidArgumentException::arraySizeNotMatch();
|
|
|
|
}
|
|
|
|
|
|
|
|
$count = count($x);
|
2016-04-27 21:57:05 +00:00
|
|
|
$meanX = Mean::arithmetic($x);
|
|
|
|
$meanY = Mean::arithmetic($y);
|
2016-04-27 21:28:01 +00:00
|
|
|
|
|
|
|
$axb = 0;
|
|
|
|
$a2 = 0;
|
|
|
|
$b2 = 0;
|
|
|
|
|
2016-11-20 21:53:17 +00:00
|
|
|
for ($i = 0; $i < $count; ++$i) {
|
2016-04-27 21:28:01 +00:00
|
|
|
$a = $x[$i] - $meanX;
|
|
|
|
$b = $y[$i] - $meanY;
|
2016-12-12 17:34:20 +00:00
|
|
|
$axb += ($a * $b);
|
|
|
|
$a2 += pow($a, 2);
|
|
|
|
$b2 += pow($b, 2);
|
2016-04-27 21:28:01 +00:00
|
|
|
}
|
|
|
|
|
2016-05-02 21:36:58 +00:00
|
|
|
$corr = $axb / sqrt((float) ($a2 * $b2));
|
2016-04-27 21:28:01 +00:00
|
|
|
|
|
|
|
return $corr;
|
|
|
|
}
|
|
|
|
}
|