简体   繁体   中英

Precision of floats with printf

As everybody knows, you have limited precision when you use printf to output the value of a float .
However, there is a trick to increase the accuracy in the output, as this example shows:

#include <stdio.h>

int main()
{
    float f = 1318926965;        /* 10 random digits */
    printf("%10.f\n", f);        /* prints only 8 correct digits */
    printf("%10d\n", *(int*)&f); /* prints all digits correctly */
    return 0;
}

and my question is, why don't people use this trick more often?

April fool?

Your "random number" 1318926965 have the same underlying representation both in decimal and floating-point form.

Try another value, like 10 . It will print as:

        10
1092616192

So to answer your question:

and my question is, why don't people use this trick more often?

Because only one day of the year is April Fools Day... The rest of the days the trick doesn't work...

Try that same trick with a different number, say 2318926965.

#include <stdio.h>

int main()
{
    float f = 2318926965;        /* 10 random digits */
    printf("%10.f\n", f);        /* prints only 8 correct digits */
    printf("%10d\n", *(int*)&f); /* prints all digits correctly */
    return 0;
}
$ gcc -Wall -O3  t.c
t.c: In function ‘main’:
t.c:7:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
$ ./a.out 
2318926848
1326069764

I don't see an increase in precision at all with your "trick" that depends on the bit representation of floats on your platform (as far as I understand it).

This thread has a few other of these "magic floats" and a way to generate them.

The limit to precision is with the floating point representation, not with printf() it is a false premise.

Moreover a single precision float is only guaranteed correct to 6 digits of precision, so the "trick" would be fooling yourself; in the general case it would not work.

If you want 10 digit floating-point numbers then you should use double precision, which is good for 15 digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM