473,769 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rational approximations

Here is an amusing toy, which may be of especial interest to the
Forthians who use rational fractions to represent real numbers.
The handling of criterion may also be interesting to some.

/* Find best rational approximation to a double */
/* by C.B. Falconer, 2006-09-07. Released to public domain */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <errno.h>

int main(int argc, char **argv)
{
int num, approx, bestnum, bestdenom;
int lastnum = 500;
double error, leasterr, value, criterion, tmp;
char *eptr;

value = 4 * atan(1.0);
if (argc 2) lastnum = strtol(argv[2], NULL, 10);
if (lastnum <= 0) lastnum = 500;
if (argc 1) {
tmp = strtod(argv[1], &eptr);
if ((0.0 >= tmp) || (tmp INT_MAX) || (ERANGE == errno)) {
puts("Invalid number, using PI");
}
else value = tmp;
}
criterion = 2 * value * DBL_EPSILON;
puts("Usage: ratvalue [number [maxnumerator]]\n"
"number defaults to PI, maxnumerator to 500");
printf("Rationa l approximation to %.*f\n", DBL_DIG, value);
for (leasterr = value, num = 1; num < lastnum; num++) {
approx = (int)(num / value + 0.5);
error = fabs((double)nu m / approx - value);
if (error < leasterr) {
bestnum = num;
bestdenom = approx;
leasterr = error;
printf("%8d / %-8d = %.*f with error %.*f\n",
bestnum, bestdenom,
DBL_DIG, (double)bestnum / bestdenom,
DBL_DIG, leasterr);
if (leasterr <= criterion) break;
}
}
return 0;
} /* main */

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Sep 7 '06 #1
10 3223
CBFalconer wrote:
Here is an amusing toy, which may be of especial interest to the
Forthians who use rational fractions to represent real numbers.
The handling of criterion may also be interesting to some.

/* Find best rational approximation to a double */
/* by C.B. Falconer, 2006-09-07. Released to public domain */
Actually, doubles are already rational numbers. The denominator
is always power of 2.

Now the numbers they approximate, that's a different story...

- Logan
Sep 8 '06 #2
CBFalconer a écrit :
Here is an amusing toy, which may be of especial interest to the
Forthians who use rational fractions to represent real numbers.
The handling of criterion may also be interesting to some.

/* Find best rational approximation to a double */
/* by C.B. Falconer, 2006-09-07. Released to public domain */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <errno.h>

int main(int argc, char **argv)
{
int num, approx, bestnum, bestdenom;
int lastnum = 500;
double error, leasterr, value, criterion, tmp;
char *eptr;

value = 4 * atan(1.0);
if (argc 2) lastnum = strtol(argv[2], NULL, 10);
if (lastnum <= 0) lastnum = 500;
if (argc 1) {
tmp = strtod(argv[1], &eptr);
if ((0.0 >= tmp) || (tmp INT_MAX) || (ERANGE == errno)) {
puts("Invalid number, using PI");
}
else value = tmp;
}
criterion = 2 * value * DBL_EPSILON;
puts("Usage: ratvalue [number [maxnumerator]]\n"
"number defaults to PI, maxnumerator to 500");
printf("Rationa l approximation to %.*f\n", DBL_DIG, value);
for (leasterr = value, num = 1; num < lastnum; num++) {
approx = (int)(num / value + 0.5);
error = fabs((double)nu m / approx - value);
if (error < leasterr) {
bestnum = num;
bestdenom = approx;
leasterr = error;
printf("%8d / %-8d = %.*f with error %.*f\n",
bestnum, bestdenom,
DBL_DIG, (double)bestnum / bestdenom,
DBL_DIG, leasterr);
if (leasterr <= criterion) break;
}
}
return 0;
} /* main */
Excuse me Chuck but I think you invoke UB in the first iteration
when we have:

num = 1
value = PI
we have then:
1/PI = 0.31830 ....
(int) 0.31830 == ZERO

Then you do

num/approx and you have a division by zero...

jacob
Sep 8 '06 #3

CBFalconer wrote:
/* Find best rational approximation to a double */
One could try to argue they solve a slightly different problem,
but continued fractions provide optimal approximations, are
easy to code, and yield fascinating results, eg.
e = 2.71828... is {2;1,2,1,1,4,1, 1,6,1,1,8,1,1,1 0,...] in
continued fraction form, and
the Golden Ratio is [1;1,1,1,1,1,1,1 ,...].

(This c.f. form of Golden Ratio means it is the real number
hardest to approximate by a rational! The Golden Ratio
bus scheduling algorithm depends on that property IIRC,
though most comp-sci algorithms called "Golden Ratio
algorithm" don't.)

As is so often the case these days, Wikipedia seems to
offer a good discussion:
http://en.wikipedia.org/wiki/Continued_fraction
value = 4 * atan(1.0);
Can't remember how to spell M_PI, eh? Neither can I, though
I usually just spell it prosaically: 3.141592635897

James Dow Allen

Sep 8 '06 #4
"James Dow Allen" <jd*********@ya hoo.comwrote:
CBFalconer wrote:
value = 4 * atan(1.0);
Can't remember how to spell M_PI, eh?
No, he can remember that M_PI is not in ISO C.

Richard
Sep 8 '06 #5
jacob navia wrote:
CBFalconer a écrit :
>Here is an amusing toy, which may be of especial interest to the
Forthians who use rational fractions to represent real numbers.
The handling of criterion may also be interesting to some.

/* Find best rational approximation to a double */
/* by C.B. Falconer, 2006-09-07. Released to public domain */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <errno.h>

int main(int argc, char **argv)
{
int num, approx, bestnum, bestdenom;
int lastnum = 500;
double error, leasterr, value, criterion, tmp;
char *eptr;

value = 4 * atan(1.0);
if (argc 2) lastnum = strtol(argv[2], NULL, 10);
if (lastnum <= 0) lastnum = 500;
if (argc 1) {
tmp = strtod(argv[1], &eptr);
if ((0.0 >= tmp) || (tmp INT_MAX) || (ERANGE == errno)) {
puts("Invalid number, using PI");
}
else value = tmp;
}
criterion = 2 * value * DBL_EPSILON;
puts("Usage: ratvalue [number [maxnumerator]]\n"
"number defaults to PI, maxnumerator to 500");
printf("Rationa l approximation to %.*f\n", DBL_DIG, value);
for (leasterr = value, num = 1; num < lastnum; num++) {
approx = (int)(num / value + 0.5);
error = fabs((double)nu m / approx - value);
if (error < leasterr) {
bestnum = num;
bestdenom = approx;
leasterr = error;
printf("%8d / %-8d = %.*f with error %.*f\n",
bestnum, bestdenom,
DBL_DIG, (double)bestnum / bestdenom,
DBL_DIG, leasterr);
if (leasterr <= criterion) break;
}
}
return 0;
} /* main */

Excuse me Chuck but I think you invoke UB in the first iteration
when we have:

num = 1
value = PI
we have then:
1/PI = 0.31830 ....
(int) 0.31830 == ZERO

Then you do

num/approx and you have a division by zero...
You are right. Sloppy of me. I added the line:

if (0 == (int)approx) continue;

after the "apprex = ..." line.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Sep 8 '06 #6
dc*****@connx.c om writes:
Reminiscient of:
http://www.acm.org/pubs/tog/Graphics...sv/ch1-4/rat.h
http://www.acm.org/pubs/tog/Graphics...sv/ch1-4/rat.c
What is?

Please provide context.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Sep 8 '06 #8
["Followup-To:" header set to comp.programmin g.]
On 2006-09-08 07:43, James Dow Allen <jd*********@ya hoo.comwrote:
CBFalconer wrote:
> value = 4 * atan(1.0);
Can't remember how to spell M_PI, eh? Neither can I, though
I usually just spell it prosaically: 3.141592635897
I just found a spare "5". Would you like to buy it?

hp
--
_ | Peter J. Holzer | Wieso sollte man etwas erfinden was nicht
|_|_) | Sysadmin WSR | ist?
| | | hj*@hjp.at | Was sonst wäre der Sinn des Erfindens?
__/ | http://www.hjp.at/ | -- P. Einstein u. V. Gringmuth in desd
Sep 8 '06 #9

Keith Thompson wrote:
dc*****@connx.c om writes:
Reminiscient of:
http://www.acm.org/pubs/tog/Graphics...sv/ch1-4/rat.h
http://www.acm.org/pubs/tog/Graphics...sv/ch1-4/rat.c

What is?
C. B. Falconer's algorithm is like the graphics gems algorithm
(continued fraction to find best numerator/denomiator to fit a float).
The gem is somewhat more generalized. CB's algorithm is more compact.
Please provide context.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Sep 13 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
2421
by: Mike Meyer | last post by:
PEP: XXX Title: A rational number module for Python Version: $Revision: 1.4 $ Last-Modified: $Date: 2003/09/22 04:51:50 $ Author: Mike Meyer <mwm@mired.org> Status: Draft Type: Staqndards Content-Type: text/x-rst Created: 16-Dec-2004 Python-Version: 2.5
20
2147
by: Mike Meyer | last post by:
This version includes the input from various and sundry people. Thanks to everyone who contributed. <mike PEP: XXX Title: A rational number module for Python Version: $Revision: 1.4 $ Last-Modified: $Date: 2003/09/22 04:51:50 $ Author: Mike Meyer <mwm@mired.org>
2
2802
by: Brian van den Broek | last post by:
Hi all, I guess it is more of a maths question than a programming one, but it involves use of the decimal module, so here goes: As a self-directed learning exercise I've been working on a script to convert numbers to arbitrary bases. It aims to take any of whole numbers (python ints, longs, or Decimals), rational numbers (n / m n, m whole) and floating points (the best I can do for reals), and convert them to any base between 2 and...
1
3485
by: lordhavemercy | last post by:
Rational Arithmetic I need a possible representstion of Rational numbers in C using Structures. It has to be a foating-point representatiobn. Each rational number has to represent/store the numerator and denumerator as integers. Structures like this can be used; struct Rational{int a, int b}; to represent a number a/b. Declaration to include Typedef struck Rational Rational; It should include only operation of addition and...
3
3393
BenTheMan
by: BenTheMan | last post by:
Hello all. I will probably be frequenting these discussions in the future. I am a graduate student in physics learning C++ on the fly. This is probably an easy quesiton, but my background in this subject is very limited. I have tried a few permutations of what I think SHOULD be right, but the compiler is giving me very cryptic errors (like 'template argument is invalid'). I cannot find any examples of what I want to do on line, and I am...
6
4647
by: penny | last post by:
In this assignment we shall look at a possible representation of rational numbers in java using objects. The java language represents rational numbers using the same representation used for other real numbers. This is the floating-point representation. However as we may all know, floating-point numbers are quite inaccurate. This means that ½ might actually be represented as 0.49998, which may not be good enough for some applications. In this...
1
2860
by: ben kipkorir | last post by:
In this assignment we shall look at a possible representation of rational numbers in java using objects. The java language represents rational numbers using the same representation used for other real numbers. This is the floating-point representation. However as we may all know, floating-point numbers are quite inaccurate. This means that ½ might actually be represented as 0.49998, which may not be good enough for some applications. In this...
135
4321
by: robinsiebler | last post by:
I've never had any call to use floating point numbers and now that I want to, I can't! *** Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) on win32. *** 0.29999999999999999 0.29999999999999999
5
4626
by: anumliaqat | last post by:
hello!! i hav a problem.my program is giving correct outputs for some inputs but wrong results for others. for example if u give (4 2 2)&(2 1 2) to it,it shows all results correct. but for (2 2 4)&(2 1 4) it gives wrong outputs. now i am unable to find which function is to be corrected and which one not. plz plz help me i have to submit it on 01 dec.
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.