LagrangeInterpolation.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. require_once "../Matrix.php";
  3. /**
  4. * Given n points (x0,y0)...(xn-1,yn-1), the following methid computes
  5. * the polynomial factors of the n-1't degree polynomial passing through
  6. * the n points.
  7. *
  8. * Example: Passing in three points (2,3) (1,4) and (3,7) will produce
  9. * the results [2.5, -8.5, 10] which means that the points are on the
  10. * curve y = 2.5x² - 8.5x + 10.
  11. *
  12. * @see http://geosoft.no/software/lagrange/LagrangeInterpolation.java.html
  13. * @author Jacob Dreyer
  14. * @author Paul Meagher (port to PHP and minor changes)
  15. *
  16. * @param x[] float
  17. * @param y[] float
  18. */
  19. class LagrangeInterpolation {
  20. public function findPolynomialFactors($x, $y) {
  21. $n = count($x);
  22. $data = array(); // double[n][n];
  23. $rhs = array(); // double[n];
  24. for ($i = 0; $i < $n; ++$i) {
  25. $v = 1;
  26. for ($j = 0; $j < $n; ++$j) {
  27. $data[$i][$n-$j-1] = $v;
  28. $v *= $x[$i];
  29. }
  30. $rhs[$i] = $y[$i];
  31. }
  32. // Solve m * s = b
  33. $m = new Matrix($data);
  34. $b = new Matrix($rhs, $n);
  35. $s = $m->solve($b);
  36. return $s->getRowPackedCopy();
  37. } // function findPolynomialFactors()
  38. } // class LagrangeInterpolation
  39. $x = array(2.0, 1.0, 3.0);
  40. $y = array(3.0, 4.0, 7.0);
  41. $li = new LagrangeInterpolation;
  42. $f = $li->findPolynomialFactors($x, $y);
  43. for ($i = 0; $i < 3; ++$i) {
  44. echo $f[$i]."<br />";
  45. }