LogarithmicBestFit.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
  3. class LogarithmicBestFit 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 = 'logarithmic';
  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() * log($xValue - $this->xOffset);
  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 exp(($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 . ' * log(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 logarithmicRegression($yValues, $xValues, $const)
  55. {
  56. foreach ($xValues as &$value) {
  57. if ($value < 0.0) {
  58. $value = 0 - log(abs($value));
  59. } elseif ($value > 0.0) {
  60. $value = log($value);
  61. }
  62. }
  63. unset($value);
  64. $this->leastSquareFit($yValues, $xValues, $const);
  65. }
  66. /**
  67. * Define the regression and calculate the goodness of fit for a set of X and Y data values.
  68. *
  69. * @param float[] $yValues The set of Y-values for this regression
  70. * @param float[] $xValues The set of X-values for this regression
  71. * @param bool $const
  72. */
  73. public function __construct($yValues, $xValues = [], $const = true)
  74. {
  75. if (parent::__construct($yValues, $xValues) !== false) {
  76. $this->logarithmicRegression($yValues, $xValues, $const);
  77. }
  78. }
  79. }