home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky sci.math:17818 sci.math.num-analysis:3750
- Path: sparky!uunet!usc!rpi!usenet.coe.montana.edu!news.u.washington.edu!zermelo.math.washington.edu!petry
- From: petry@zermelo.math.washington.edu (David Petry)
- Newsgroups: sci.math,sci.math.num-analysis
- Subject: Re: Approximating decimal fractions with proper fractions
- Date: 8 Jan 1993 04:07:18 GMT
- Organization: University of Washington, Mathematics, Seattle
- Lines: 80
- Distribution: na
- Message-ID: <1iiulmINNf0r@shelley.u.washington.edu>
- References: <C0ICCG.1BJ@hsi.com>
- NNTP-Posting-Host: zermelo.math.washington.edu
- Keywords: fraction, approximation, number theory
-
- In article <C0ICCG.1BJ@hsi.com> rogerh@code3 (Roger Harrison) writes:
- >I am looking for an algorithm (preferably a computationally cheap one)
- >to approximate a decimal fraction with a proper fraction for display
- >purposes. The ideal algorithm would take a decimal fraction and the
- >maximum number of digits in the result's denominator to determine the
- >proper fraction (in numerator/denominator form) which best approximates
- >the original decimal fraction.
- >
- >Stated more precisely:
- >
- >Given the decimal fraction F, ( F = x/y where x < y, y = 10^n, n >= 1 ),
- >what is the proper fraction, a/b, that best approximates F if b < 10^m,
- >m >= 1, m <= n.
-
-
- The following short C program will do the trick. It works by
- converting a real number into a contiunued fraction. I'm not sure
- if all C math libraries have the function modf, so there might be
- some problems on some systems.
-
-
- David Petry
-
-
-
- #include <stdio.h>
- #include <math.h>
-
-
- #define rational struct rat_
- rational {
- int a,b;
- };
-
-
-
- #define rational_to_real(r) ((double) (r).a / (double) (r).b)
-
- rational
- real_to_rational(r, err) double r, err;
- {
- int k=1, A;
- rational rat1, rat2, rat3;
- double r1, rA;
- r1 = modf(r, &rA);
- A = (int) rA;
- rat1.a = 1;
- rat1.b = 0;
- rat2.a = A;
- rat2.b = 1;
- while ( (k++<40) && (fabs(rational_to_real(rat2) - r) > err) ) {
- r1 = modf(1./r1, &rA);
- A = (int) rA;
- rat3.a = A*rat2.a + rat1.a;
- rat3.b = A*rat2.b + rat1.b;
- rat1 = rat2;
- rat2 = rat3;
- }
- return rat2;
- }
-
-
-
- void
- print_rat(rat) rational rat;
- {
- printf("%d/%d", rat.a, rat.b);
- }
-
- main () {
- double r;
- rational rat;
- while (1) {
- printf("Enter real >> ");
- scanf("%lf", &r);
- rat = real_to_rational(r, .00000001);
- printf("%d/%d\n", rat.a, rat.b);
- }
- }
-
-