🔬41. Converting Num to Rat in Perl 6

In Perl 6, you can easily coerce numerical values from one type to another. One of the interesting conversions is Num to Rat.

For example, take the value of π and convert it to a fraction:

$ perl6 -e'say pi.Rat.perl'
<355/113>

Indeed, 355/113 is 3.14159292035398, which is close to π. The default maximum error is built-in in Rakudo and is set to 10–6.

Algorithm

The implementation of the method is located in the src/core/Num.pm file. Let us read it line by line. First, the signature:

method Rat(Num:D: Real $epsilon = 1.0e-6, :$fat)

Here, you see $epsilon, a positional parameter with the default value, and a flag, :$fat, which you should set if you want to have a FatRat value. The first action is creating a variable that is either a Rat or a FatRat:

my \RAT = $fat ?? FatRat !! Rat;

The next step is a test whether the number is a number and is not infinite:

At this point, we have a first approximation: the $num variable contains an integer part. The rest is shown in the picture:

Seriously speaking, the rest of the method is an implementation of the numerical approximation, which tries to find such numerator and denominator so that the fraction is close enough to the value in question.