Math   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 0
cbo 0
dl 0
loc 43
ccs 22
cts 22
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B linearRegression() 0 32 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