Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // the contfrac(x,y) function outputs an array starting from 0 to y - 1 of all the terms in the continued fraction of x
- // 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)
- function contfrac($constant, $upto=5) {
- $frac[0] = floor($constant);
- if ($frac[0] - $constant) { $a[0] = 1/($constant-floor($constant)); }
- else { $a[0] = 0; }
- for ($i = 0; $i <= $upto; $i++) {
- if ($a[$i]-floor($a[$i]) != 0) { $a[$i+1] = 1/($a[$i]-floor($a[$i])); }
- else { $a[$i+1] = 0; }
- $frac[$i+1] = floor($a[$i]);
- }
- return $frac;
- }
- // optional :
- $upto = 10;
- for ($i = 1; $i > 0; $i++) {
- $u = readline(">");
- $u = str_replace(array("pi()","pi","_&#/!","^"),array("_&#/!","pi()","pi()","**"),$u);
- eval("\$f = " . $u . ";");
- if ($f < 0) { $sgn = "-"; }
- else { $sgn = ""; }
- $u = $sgn . "($u)";
- eval("\$frac = contfrac(" . $u . ", \$upto);");
- print "[$sgn" . $frac[0] . "; " . $frac[1];
- for ($i = 2; $i <= $upto; $i++) {
- print ", " . $frac[$i];
- }
- print ", ...]\n";
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement