contFrac(x,n)returns a Fraction that is very close to x using continued fraction approximation. The function is recursive and n is a depth countdown. Using 30 for n will ensure that any rational value for x with six-digit (or less) denominator will be caught and output as a Fraction equal to x. (This also catches many rationals with larger denominators.)

For irrationals and other rationals with bigger denominators, either the algorithm stops after n iterations or when the kth integer part is over 10^8. For example, contFrac(10+10**-9,n) will always output Fraction(10,1). But contFrac(10+10**-8,1) will output Fraction(999999911,99999991).

sub contFrac {

my $real = shift;

my $counter = shift;

my $intpart = floor($real);

my $partial;

if (($real - $intpart > 1/10**8) and ($counter>0))

{$partial = contFrac(1/($real - $intpart ), $counter-1);}

else {return Fraction($intpart,1)};

return 1/$partial+$intpart ;

};