default
[ class tree: default ] [ index: default ] [ all elements ]

Source for file polyfit.php

Documentation is available at polyfit.php

  1. <?php
  2. require_once "../Matrix.php";
  3. /*
  4. * @package JAMA
  5. * @author Michael Bommarito
  6. * @author Paul Meagher
  7. * @version 0.1
  8. *
  9. * Function to fit an order n polynomial function through
  10. * a series of x-y data points using least squares.
  11. *
  12. * @param $X array x values
  13. * @param $Y array y values
  14. * @param $n int order of polynomial to be used for fitting
  15. * @returns array $coeffs of polynomial coefficients
  16. * Pre-Conditions: the system is not underdetermined: sizeof($X) > $n+1
  17. */
  18. function polyfit($X$Y$n{  
  19.   for ($i 0$i sizeof($X)$i++
  20.       for ($j 0$j <= $n$j++
  21.         $A[$i][$jpow($X[$i]$j);
  22.   for ($i=0$i sizeof($Y)$i++)
  23.     $B[$iarray($Y[$i]);   
  24.   $matrixA new Matrix($A);
  25.   $matrixB new Matrix($B);
  26.   $C $matrixA->solve($matrixB);
  27.   return $C->getMatrix(0$n01);
  28. }
  29.  
  30. function printpoly$C null {
  31.   for($i $C->1$i >= 0$i-- {
  32.     $r $C->get($i0);
  33.     if abs($r<= pow(10-9) )
  34.       $r 0;
  35.     if ($i == $C->1)
  36.       echo $r "x<sup>$i</sup>";
  37.     else if ($i $C->1)
  38.       echo " + " $r "x<sup>$i</sup>";
  39.     else if ($i == 0)
  40.       echo " + " $r;
  41.   }
  42. }
  43.  
  44. $X array(0,1,2,3,4,5);
  45. $Y array(4,3,12,67,228579);
  46. $points new Matrix(array($X$Y));
  47. $points->toHTML();
  48. printpoly(polyfit($X$Y4));
  49.  
  50. echo '<hr />';
  51.  
  52. $X array(0,1,2,3,4,5);
  53. $Y array(1,2,5,10,1726);
  54. $points new Matrix(array($X$Y));
  55. $points->toHTML();
  56. printpoly(polyfit($X$Y2));
  57.  
  58. echo '<hr />';
  59.  
  60. $X array(0,1,2,3,4,5,6);
  61. $Y array(-90,-104,-178,-252,-2611604446);
  62. $points new Matrix(array($X$Y));
  63. $points->toHTML();
  64. printpoly(polyfit($X$Y5));
  65.  
  66. echo '<hr />';
  67.  
  68. $X array(0,1,2,3,4);
  69. $Y array(mt_rand(010)mt_rand(4080)mt_rand(240400)mt_rand(18002215)mt_rand(80009000))
  70. $points new Matrix(array($X$Y));
  71. $points->toHTML();
  72. printpoly(polyfit($X$Y3));
  73. ?>

Documentation generated on Wed, 22 Apr 2009 09:01:31 +0200 by phpDocumentor 1.4.1