LinearBestFit.php 2.1 KB

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