Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
[Rat] explain overflow of denominator and fallback to Num
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| =begin pod | ||
| =head1 Rat | ||
| class Rat is Cool does Rational[Int, UInt64] { ... } | ||
| C<Rat> objects store rational numbers as a pair of a numerator and | ||
| denominator. Number literals with a dot but without exponent produce | ||
| C<Rat>s. | ||
| 3.1; # Rat.new(31, 10) | ||
| That way arithmetic with short dotted-decimal numbers does not suffer | ||
| from floating point errors. | ||
| To prevent the numerator and denominator to become pathologically large, | ||
| the denominator is limited to 64 bit storage. On overflow of the denomniator | ||
| a C<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() | ||
| =end pod |