Advertisement
apexsquirt

Continued fractions with PHP

Feb 26th, 2018
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.19 KB | None | 0 0
  1. <?php
  2.  
  3. // the contfrac(x,y) function outputs an array starting from 0 to y - 1 of all the terms in the continued fraction of x
  4. // due to computational errors, php may output erroneous results after a few terms (eg : using 1/2+sqrt(5)/2 as x doesn't always output ones past 38 terms and sqrt(2) doesn't always output two's after the sole 1 at contfrac(sqrt(2),y)[0] when y >= 20 on my version)
  5.  
  6. function contfrac($constant, $upto=5) {
  7.     $frac[0] = floor($constant);
  8.     if ($frac[0] - $constant) { $a[0] = 1/($constant-floor($constant)); }
  9.     else { $a[0] = 0; }
  10.     for ($i = 0; $i <= $upto; $i++) {
  11.         if ($a[$i]-floor($a[$i]) != 0) { $a[$i+1] = 1/($a[$i]-floor($a[$i])); }
  12.         else { $a[$i+1] = 0; }
  13.         $frac[$i+1] = floor($a[$i]);
  14.     }
  15.     return $frac;
  16. }
  17.  
  18. // optional :
  19. $upto = 10;
  20. for ($i = 1; $i > 0; $i++) {
  21.     $u = readline(">");
  22.     $u = str_replace(array("pi()","pi","_&#/!","^"),array("_&#/!","pi()","pi()","**"),$u);
  23.     eval("\$f = " . $u . ";");
  24.     if ($f < 0) { $sgn = "-"; }
  25.     else { $sgn = ""; }
  26.     $u = $sgn . "($u)";
  27.     eval("\$frac = contfrac(" . $u . ", \$upto);");
  28.     print "[$sgn" . $frac[0] . "; " . $frac[1];
  29.     for ($i = 2; $i <= $upto; $i++) {
  30.         print ", " . $frac[$i];
  31.     }
  32.     print ", ...]\n";
  33. }
  34.  
  35. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement