473,396 Members | 2,085 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Correct precision with printf

I read the thread Floating point rounding error and
I saw Richard Heathfield's description with several
lines like:
0.1 = 1/2 = 0.5 - too large
0.01 = 1/4 = 0.25 - too large
0.001 = 1/8 = 0.125 - too large
....

And I wanted to write such a program that output
lines like that. My attempt is below, and I don't
know how I should print the third column, with
printf I either get too low precision or a lot of
zeros after the first lines. Right now I just
have %.20f in the format string, but I wonder
how I can do it like Heathfield did and remove
trailing zeroes. Otherwise I wonder if my program
is a correct C program. Thanks!

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>

/* Examines the binary representation in the array to
see if it is smaller or larger than value.
Prints a new line containing the info and returns
the result of the comparison. */
int examine(char *data, size_t length, double value)
{
size_t i;
int num, den;
double result;

/* Shorten the length */
i = length;
while (i-- && data[i] == 0) {
length--;
}
assert(length != 0);

num = 0;
den = 1;
printf("0.");
for (i = 0; i < length; i++) {
den *= 2;
num *= 2;
if (data[i] != 0) {
putchar('1');
num++;
}
else
putchar('0');
}

result = (double)num/den;
printf(" = %d/%d = %.20f", num, den, result);
if (result == value) {
printf(" - same\n");
return 0;
}
else if (result value) {
printf(" - too large\n");
return 1;
}
else {
printf(" - too small\n");
return -1;
}
}

int main(int argc, char *argv[])
{
char array[17] = { 0 };
double val;
int i;
int cmp;

if (argc < 2)
return EXIT_FAILURE;

val = strtod(argv[1], NULL);
if (errno != 0)
return EXIT_FAILURE;

array[0] = 1;
for (i = 1; i < 17; i++) {
cmp = examine(array, i, val);
if (cmp == 0)
return 0;
else if (cmp < 1) {
array[i] = 1;
}
else {
array[i - 1] = 0;
array[i] = 1;
}
}
return EXIT_SUCCESS;
}

Jun 17 '07 #1
4 2245
ba******@hushmail.com said:
I read the thread Floating point rounding error and
I saw Richard Heathfield's description with several
lines like:
0.1 = 1/2 = 0.5 - too large
0.01 = 1/4 = 0.25 - too large
0.001 = 1/8 = 0.125 - too large
...

And I wanted to write such a program that output
lines like that. My attempt is below,
Applause!

For extra credit, make it work to an arbitrary precision.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 17 '07 #2

<ba******@hushmail.comha scritto nel messaggio
news:11*********************@n60g2000hse.googlegro ups.com...
>I read the thread Floating point rounding error and
I saw Richard Heathfield's description with several
lines like:
0.1 = 1/2 = 0.5 - too large
0.01 = 1/4 = 0.25 - too large
0.001 = 1/8 = 0.125 - too large
...

And I wanted to write such a program that output
lines like that. My attempt is below, and I don't
know how I should print the third column, with
printf I either get too low precision or a lot of
zeros after the first lines. Right now I just
have %.20f in the format string, but I wonder
how I can do it like Heathfield did and remove
trailing zeroes. Otherwise I wonder if my program
is a correct C program. Thanks!
Use the %g conversion instead of %f.
BTW, have you tried it with an argument <= 0 or >= 1?
(And before returning EXIT_FAILURE I'd give the user a clue of why
the program failed.)
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>

/* Examines the binary representation in the array to
see if it is smaller or larger than value.
Prints a new line containing the info and returns
the result of the comparison. */
int examine(char *data, size_t length, double value)
{
size_t i;
int num, den;
double result;

/* Shorten the length */
i = length;
while (i-- && data[i] == 0) {
length--;
}
assert(length != 0);

num = 0;
den = 1;
printf("0.");
for (i = 0; i < length; i++) {
den *= 2;
num *= 2;
if (data[i] != 0) {
putchar('1');
num++;
}
else
putchar('0');
}

result = (double)num/den;
printf(" = %d/%d = %.20f", num, den, result);
if (result == value) {
printf(" - same\n");
return 0;
}
else if (result value) {
printf(" - too large\n");
return 1;
}
else {
printf(" - too small\n");
return -1;
}
}

int main(int argc, char *argv[])
{
char array[17] = { 0 };
double val;
int i;
int cmp;

if (argc < 2)
return EXIT_FAILURE;

val = strtod(argv[1], NULL);
if (errno != 0)
return EXIT_FAILURE;

array[0] = 1;
for (i = 1; i < 17; i++) {
cmp = examine(array, i, val);
if (cmp == 0)
return 0;
else if (cmp < 1) {
array[i] = 1;
}
else {
array[i - 1] = 0;
array[i] = 1;
}
}
return EXIT_SUCCESS;
}

Jun 17 '07 #3
On Jun 17, 10:20 pm, "Army1987" <please....@for.itwrote:
<banan...@hushmail.comha scritto nel messaggionews:11*********************@n60g2000hse. googlegroups.com...
I read the thread Floating point rounding error and
I saw Richard Heathfield's description with several
lines like:
0.1 = 1/2 = 0.5 - too large
0.01 = 1/4 = 0.25 - too large
0.001 = 1/8 = 0.125 - too large
...
And I wanted to write such a program that output
lines like that. My attempt is below, and I don't
know how I should print the third column, with
printf I either get too low precision or a lot of
zeros after the first lines. Right now I just
have %.20f in the format string, but I wonder
how I can do it like Heathfield did and remove
trailing zeroes. Otherwise I wonder if my program
is a correct C program. Thanks!

Use the %g conversion instead of %f.
Thanks! I missed that when I read about the specifiers,
didn't know it was that easy.
BTW, have you tried it with an argument <= 0 or >= 1?
(And before returning EXIT_FAILURE I'd give the user a clue of why
the program failed.)
Yeah, I knew of those two points, I should have said that.
But thanks for pointing that out.

Jun 18 '07 #4
ba******@hushmail.com writes:
I read the thread Floating point rounding error and
I saw Richard Heathfield's description with several
lines like:
0.1 = 1/2 = 0.5 - too large
0.01 = 1/4 = 0.25 - too large
0.001 = 1/8 = 0.125 - too large
...

And I wanted to write such a program that output
lines like that. My attempt is below, and I don't
know how I should print the third column, with
printf I either get too low precision or a lot of
zeros after the first lines. Right now I just
have %.20f in the format string, but I wonder
how I can do it like Heathfield did and remove
trailing zeroes.
%g has already been suggested, but %.*g (or %.*f) has not. This lets
you pass the desired precision as a parameter to *printf function.
The variable 'length' is a good first stab at the right value.

--
Ben.
Jun 18 '07 #5

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

Similar topics

5
by: Robert | last post by:
Hello all, I use clock() to measure the time cost in my program. But the t_clock always be the multiply of 10, for example 10, 20, 30, 40,... And I want to get the precision of 1, such as 11,...
5
by: DAVID SCHULMAN | last post by:
I've been trying to perform a calculation that has been running into an underflow (insufficient precision) problem in Microsoft Excel, which calculates using at most 15 significant digits. For this...
15
by: michael.mcgarry | last post by:
Hi, I have a question about floating point precision in C. What is the minimum distinguishable difference between 2 floating point numbers? Does this differ for various computers? Is this...
1
by: blackswift | last post by:
hello, program: double x; scanf("%lf", &x); printf("%lf\n", x); input: 3.14159265358979
6
by: R.Biloti | last post by:
Hi folks I wrote the naive program to show up the unit roundoff (machine precision) for single and double precision: #include <stdio.h> int main (void) { double x;
5
by: artifact.one | last post by:
Hello. Is there any reliable way to determine the number of digits of precision given by the float/double type? I read somewhere that the C99 standard guarantees six digits of precision with...
6
by: Enrique Cruiz | last post by:
Hi guys, I use LUTs to accelerate certain parts of my app. The LUTs contain float numbers, and I generated the numbers very precisely, up to 10 decimals. All seems fine, however, when I printf...
2
by: whatdoineed2do | last post by:
#include <iostream> using namespace std; void convert(const double& d) { cout << "before=" << d << " after="; cout.precision(15); cout << d << endl; }
14
by: pereges | last post by:
I would like to have precision upto atleast 8 digits in my numerical computation program. I have tried using doubles but I keep getting results only till 6 places after decimal. eg. #include...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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,...

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.