Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Approximation with chain fractions

by ambrus (Abbot)
on Jan 24, 2005 at 07:55 UTC ( #424519=snippet: print w/ replies, xml ) Need Help??
Description:

Approximate any real number $x with chain fractions.

I'm not the first one offering code on this, see Continued Fractions.

#use bignum "a", 32; # uncomment for greater precision
$x = 2**(1/12); # change this to any number you like
print $x, "\n"; ($p, $q, $r, $s) = (0, 1, 1, 0); 
{ 
$n = int(($p - $x*$q) / ($x*$s - $r)); ($p, $q) = ($p + $n*$r, $q + $n
+*$s); print $p, "/", $q, " = ", $y = $p/$q, "\n"; $y == $x and last; 
$n = int(($r - $x*$s) / ($x*$q - $p)); ($r, $s) = ($r + $p*$n, $s + $q
+*$n); print $r, "/", $s, " = ", $y = $r/$s, "\n"; $y == $x and last; 
redo; }
Replies are listed 'Best First'.
Re: Approximation with chain fractions
by Anonymous Monk on Jan 24, 2005 at 19:31 UTC
    Can you add code tags please?
Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://424519]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2016-07-23 13:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What is your favorite alternate name for a (specific) keyboard key?


















    Results (220 votes). Check out past polls.