Math::linearRegression()   B
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 32
ccs 22
cts 22
cp 1
rs 8.5806
cc 4
eloc 20
nc 8
nop 1
crap 4
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