Here's how I would do it:
use warnings; use strict; my $number = shift; my $error = $number+1; my $denom = 1; while ($error) { my $num = int($number * $denom + .5); if (abs($num/$denom - $number) < $error) { $error = abs($num/$denom - $number); print "$num/$denom\t\terr=$error\n"; } exit if ++$denom > 999; }
Sample output:
$ perl fract.pl 3.14159265358979323 3/1 err=0.141592653589793 13/4 err=0.108407346410207 16/5 err=0.0584073464102071 19/6 err=0.0250740130768734 22/7 err=0.00126448926734968 179/57 err=0.00124177639681067 201/64 err=0.000967653589793116 223/71 err=0.000747583167258092 245/78 err=0.000567012564152147 267/85 err=0.000416183001557879 289/92 err=0.000288305763706198 311/99 err=0.000178512175651679 333/106 err=8.32196275291075e-05 355/113 err=2.66764189404967e-07
That last (355/113) is actually an extremely good value; you don't get better until:
52163/16604 err=2.66213257216208e-07

In reply to Re: Percentages to Fractions by ysth
in thread Percentages to Fractions by David Caughell

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.