| 1441 |
ariadna |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
|
|
|
4 |
|
|
|
5 |
class LinearBestFit extends BestFit
|
|
|
6 |
{
|
|
|
7 |
/**
|
|
|
8 |
* Algorithm type to use for best-fit
|
|
|
9 |
* (Name of this Trend class).
|
|
|
10 |
*/
|
|
|
11 |
protected string $bestFitType = 'linear';
|
|
|
12 |
|
|
|
13 |
/**
|
|
|
14 |
* Return the Y-Value for a specified value of X.
|
|
|
15 |
*
|
|
|
16 |
* @param float $xValue X-Value
|
|
|
17 |
*
|
|
|
18 |
* @return float Y-Value
|
|
|
19 |
*/
|
|
|
20 |
public function getValueOfYForX(float $xValue): float
|
|
|
21 |
{
|
|
|
22 |
return $this->getIntersect() + $this->getSlope() * $xValue;
|
|
|
23 |
}
|
|
|
24 |
|
|
|
25 |
/**
|
|
|
26 |
* Return the X-Value for a specified value of Y.
|
|
|
27 |
*
|
|
|
28 |
* @param float $yValue Y-Value
|
|
|
29 |
*
|
|
|
30 |
* @return float X-Value
|
|
|
31 |
*/
|
|
|
32 |
public function getValueOfXForY(float $yValue): float
|
|
|
33 |
{
|
|
|
34 |
return ($yValue - $this->getIntersect()) / $this->getSlope();
|
|
|
35 |
}
|
|
|
36 |
|
|
|
37 |
/**
|
|
|
38 |
* Return the Equation of the best-fit line.
|
|
|
39 |
*
|
|
|
40 |
* @param int $dp Number of places of decimal precision to display
|
|
|
41 |
*/
|
|
|
42 |
public function getEquation(int $dp = 0): string
|
|
|
43 |
{
|
|
|
44 |
$slope = $this->getSlope($dp);
|
|
|
45 |
$intersect = $this->getIntersect($dp);
|
|
|
46 |
|
|
|
47 |
return 'Y = ' . $intersect . ' + ' . $slope . ' * X';
|
|
|
48 |
}
|
|
|
49 |
|
|
|
50 |
/**
|
|
|
51 |
* Execute the regression and calculate the goodness of fit for a set of X and Y data values.
|
|
|
52 |
*
|
|
|
53 |
* @param float[] $yValues The set of Y-values for this regression
|
|
|
54 |
* @param float[] $xValues The set of X-values for this regression
|
|
|
55 |
*/
|
|
|
56 |
private function linearRegression(array $yValues, array $xValues, bool $const): void
|
|
|
57 |
{
|
|
|
58 |
$this->leastSquareFit($yValues, $xValues, $const);
|
|
|
59 |
}
|
|
|
60 |
|
|
|
61 |
/**
|
|
|
62 |
* Define the regression and calculate the goodness of fit for a set of X and Y data values.
|
|
|
63 |
*
|
|
|
64 |
* @param float[] $yValues The set of Y-values for this regression
|
|
|
65 |
* @param float[] $xValues The set of X-values for this regression
|
|
|
66 |
*/
|
|
|
67 |
public function __construct(array $yValues, array $xValues = [], bool $const = true)
|
|
|
68 |
{
|
|
|
69 |
parent::__construct($yValues, $xValues);
|
|
|
70 |
|
|
|
71 |
if (!$this->error) {
|
|
|
72 |
$this->linearRegression($yValues, $xValues, (bool) $const);
|
|
|
73 |
}
|
|
|
74 |
}
|
|
|
75 |
}
|