Skip to content

Instantly share code, notes, and snippets.

@robhammond
Created June 8, 2018 17:01
Show Gist options
  • Save robhammond/13e79c9bc96804abfb1abb569755fd21 to your computer and use it in GitHub Desktop.
Save robhammond/13e79c9bc96804abfb1abb569755fd21 to your computer and use it in GitHub Desktop.
Convert decimal numbers to fractions
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