Created
June 8, 2018 17:01
-
-
Save robhammond/13e79c9bc96804abfb1abb569755fd21 to your computer and use it in GitHub Desktop.
Convert decimal numbers to fractions
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
sub float2rat { | |
my $x = shift; | |
my $tolerance = 1.0E-6; | |
my $h1 = 1; | |
my $h2 = 0; | |
my $k1 = 0; | |
my $k2 = 1; | |
my $b = $x; | |
do { | |
my $a = floor($b); | |
my $aux = $h1; | |
$h1 = $a * $h1 + $h2; | |
$h2 = $aux; | |
$aux = $k1; | |
$k1 = $a * $k1 + $k2; | |
$k2 = $aux; | |
$b = 1/($b-$a); | |
} | |
while (abs($x - $h1 / $k1) > $x * $tolerance); | |
return $h1 . "/" . $k1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment