Skip to content

Commit cfa8f0e

Browse files
committed
[Rat] explain overflow of denominator and fallback to Num
1 parent 28057e9 commit cfa8f0e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

lib/Rat.pod

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
=begin pod
2+
3+
=head1 Rat
4+
5+
class Rat is Cool does Rational[Int, UInt64] { ... }
6+
7+
C<Rat> objects store rational numbers as a pair of a numerator and
8+
denominator. Number literals with a dot but without exponent produce
9+
C<Rat>s.
10+
11+
3.1; # Rat.new(31, 10)
12+
13+
That way arithmetic with short dotted-decimal numbers does not suffer
14+
from floating point errors.
15+
16+
To prevent the numerator and denominator to become pathologically large,
17+
the denominator is limited to 64 bit storage. On overflow of the denomniator
18+
a C<Num> (floating-poing number) is returned instead.
19+
20+
For example this function crudely approximates a square root, and overflows
21+
the denominator quickly:
22+
23+
sub approx-sqrt($n, $iterations) {
24+
my $x = $n;
25+
$x = ($x + $n / $x) / 2 for ^$iterations;
26+
return $x;
27+
}
28+
say approx-sqrt(2, 5).WHAT; # Rat()
29+
say approx-sqrt(2, 10).WHAT; # Num()
30+
31+
32+
=end pod

0 commit comments

Comments
 (0)