perl6/doc/lib/Rat

doc src
The sigil serves both as rough type constraint, and as an indicator as to whether the contents of the variable flatten in list context. See also the documentation in L<List>.
(title) class Rat
    class Rat is Cool does Rational[Int, UInt64] { ... }

 
Rat objects store rational numbers as a pair of a numerator and denominator. Number literals with a dot but without exponent produce Rat s.
    3.1;    # Rat.new(31, 10)

 
Thus arithmetic with short dotted-decimal numbers does not suffer from floating point errors. To prevent the numerator and denominator from becoming pathologically large, the denominator is limited to 64 bit storage. On overflow of the denomniator a Num (floating-poing number) is returned instead. For example this function crudely approximates a square root, and overflows the denominator quickly:
    sub approx-sqrt($n, $iterations) {
        my $x = $n;
        $x = ($x + $n / $x) / 2 for ^$iterations;
        return $x;
    }
    say approx-sqrt(2, 5).WHAT;     # Rat()
    say approx-sqrt(2, 10).WHAT;    # Num()

 
If you want arbitrary precision arithmetic with rational numbers, use the FatFat type instead. Rat objects are immutable.

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.
Email:
Name: