Re: Fast Reduced Fractions...


[Prev][Next][Index][Thread]

Re: Fast Reduced Fractions...



Yes, this would be dreadfully slow.  It would be better for you to try
different =denominators=, then compute the closest possible numerator, and
compare that.  (I don't know if there is a general "single pass" formula;
the only kind of solution I can imagine is iterative.)

Something like the following works on my machine (but is still quite slow).
There is probably some adjustment that can be added to choose the
denominator more intelligently; the main reason that this routine takes so
long is that it tries every possible denominator starting at 2.

int x, y=1;
double fnum, MyDec = 99999998./99999999.;

do
{
  /* increase denominator, and compute x as
     nearest integer approximation to numerator */
  x = (fnum = (++y) * MyDec) + 0.5;
} while (fabs(x-fnum) > .00000000000001);

printf("%18.15f is (approximately) %i/%i\n", MyDec, x, y);

-----Original Message-----
From: Open discussion of TI Graphing Calculators
[mailto:CALC-TI@LISTS.PPP.TI.COM]On Behalf Of Thomas J. Hruska
Sent: Monday, March 26, 2001 12:37 AM
To: CALC-TI@LISTS.PPP.TI.COM
Subject: Fast Reduced Fractions...


Hello, I'm currently hunting for a way to generate a reduced fraction from
a decimal using C (the language doesn't matter, I'm after a formula).  I've
found a solution, but as you will see, it is not pretty with large values
for the numerator and denominator:

int x, y;
double MyDec = 99999998/99999999;

y = 2;
x = 1;
while(abs((double)x/(double)y - MyDec) > .00000000000001)
{
  x++;
  if (x == y)
  {
    x = 1;
    y++;
  }
}
printf("%i/%i\n", x, y);

Yes, it should work (untested and for good reason)...but with the above
MyDec value it will take a *LOOONG* time to process (and might print a
close but wrong answer). ...

******************************************************************
* To UNSUBSCRIBE, send an email TO: listserv@lists.ppp.ti.com
* with a message (not the subject) that reads SIGNOFF CALC-TI
*
* Archives at http://peach.ease.lsoft.com/archives/calc-ti.html
******************************************************************


References: