in reply to Percentages to Fractions
0.35 = 1/28 - 1/6 - 1/60 = 7/20 0.35 = int (1/0.35) - int (1/(1 - int(1/0.35))) ...
use strict; use warnings; while (<DATA>) { chomp; my ($den, $div, $error) = fraction($_); print "$_\t$den/$div\n"; } sub fraction { my $value = shift; my $a = 1; my $b = int(1 / $value); my $c = (1 / $b) - $value; # error return ($a, $b, $c) if $c < 0.0005; my ($d, $e, $f) = fraction($c); my $g = $a * $e - $d * $b; my $h = $b * $e; for (2,3,5,7) { # reduces 2/4 => 1/2, 3/27 => 1/9, etc. ($g, $h) = reduce($g, $h, $_); } return ($g, $h, $f); } sub reduce { my ($a, $b, $base) = @_; while ($a % $base == 0 && $b % $base == 0) { $a = $a / $base; $b = $b / $base; } return ($a, $b); } __DATA__ 0.035 0.037 0.039 0.041 0.043 0.046 0.048 0.058 0.068 0.078 0.35 0.37 0.39 0.41 0.43 0.46 0.48 0.58 0.68 0.78
0.035 7/200 0.037 1/27 0.039 974/24975 0.041 41/1000 0.043 1/23 0.046 596/12957 0.048 479/9980 0.058 1197/20638 0.068 277/4074 0.078 175/2244 0.35 7/20 0.37 57/154 0.39 6311/16182 0.41 4961/12100 0.43 43/100 0.46 23/50 0.48 47/98 0.58 2081/3588 0.68 151/222 0.78 103/132
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Percentages to Fractions
by tilly (Archbishop) on Feb 03, 2004 at 23:00 UTC | |
by ysth (Canon) on Feb 04, 2004 at 00:24 UTC |