473,789 Members | 2,122 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2266
ba******@hushma il.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******@hushm ail.comha scritto nel messaggio
news:11******** *************@n 60g2000hse.goog legroups.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...@hushm ail.comha scritto nel messaggionews:1 1************** *******@n60g200 0hse.googlegrou ps.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******@hushma il.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
4781
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, 12, 13, 14... How can I change the t_clock's precision? Code list below: //-----------------
5
6092
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 purpose, that isn't enough. I was reading a book about some of the financial scandals of the 1990s called "Inventing Money: The Story of Long-Term Capital Management and the Legends Behind it" by Nicholas Dunbar. On page 95, he mentions that...
15
3933
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 the EPSILON? I know in float.h a FLT_EPSILON is defined to be 10^-5. Does this mean that the computer cannot distinguish between 2 numbers that differ by less than this epsilon?
1
1444
by: blackswift | last post by:
hello, program: double x; scanf("%lf", &x); printf("%lf\n", x); input: 3.14159265358979
6
5717
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
2408
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 the float type, although I can't seem to find this information now. A cursory search through the C99 pdf doesn't bring
6
2494
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 the numbers in the LUT, I do not get the same exact numbers. The first 6 decimals are ok, but it got beserk after that. To illustrate further: float myLUT = ;
2
2668
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
8541
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 <stdio.h> #define M_PI 3.14159265358979323846 /* M_PI is not defined in math.h according to my compiler*/ int main(void) {
0
9499
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10374
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10121
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9969
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
8995
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
7519
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
5404
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...
0
5539
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.