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("Rational approximation to %.*f\n", DBL_DIG, value);
for (leasterr = value, num = 1; num < lastnum; num++) {
approx = (int)(num / value + 0.5);
error = fabs((double)num / 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> 10 3192
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
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("Rational approximation to %.*f\n", DBL_DIG, value);
for (leasterr = value, num = 1; num < lastnum; num++) {
approx = (int)(num / value + 0.5);
error = fabs((double)num / 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
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,10,...] 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
"James Dow Allen" <jd*********@yahoo.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
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("Rational approximation to %.*f\n", DBL_DIG, value); for (leasterr = value, num = 1; num < lastnum; num++) { approx = (int)(num / value + 0.5); error = fabs((double)num / 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.com, 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/googlegroupsreply/>
["Followup-To:" header set to comp.programming.]
On 2006-09-08 07:43, James Dow Allen <jd*********@yahoo.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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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 $...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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
|
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....
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
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...
| |