Code

< 40 %
40-60 %
> 60 %
1
<?php
2
3
namespace Innmind\ProvisionerBundle;
4
5
/**
6
 * Small helper to linearize data points
7
 */
8
class Math
9
{
10
    /**
11
     * Determine slope and intercept variables of the affine function
12
     * that best fit the given datapoints
13
     *
14
     * @param array $data Array keys as x axis and values as y axis
15
     *
16
     * @return array Like ['slope' => float, 'intercept' => float]
17
     */
18 6
    public static function linearRegression(array $data)
19
    {
20 6
        $count = count($data);
21 6
        $x = array_keys($data);
22 6
        $y = array_values($data);
23
24 6
        foreach ($x as &$value) {
25 6
            $value = (float) $value;
26 6
        }
27
28 6
        foreach ($y as &$value) {
29 6
            $value = (float) $value;
30 6
        }
31
32 6
        $xSum = array_sum($x);
33 6
        $ySum = array_sum($y);
34 6
        $xxSum = 0;
35 6
        $xySum = 0;
36
37 6
        for ($i = 0; $i < $count; $i++) {
38 6
            $xySum += $x[$i] * $y[$i];
39 6
            $xxSum += $x[$i] * $x[$i];
40 6
        }
41
42 6
        $slope = (($count * $xySum) - ($xSum * $ySum)) / (($count * $xxSum) - ($xSum * $xSum));
43 6
        $intercept = ($ySum - ($slope * $xSum)) / $count;
44
45
        return [
46 6
            'slope' => $slope,
47
            'intercept' => $intercept
48 6
        ];
49
    }
50
}
51