Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 213
Mr Lister Avatar asked Apr 01 '12 08:04

Mr Lister


People also ask

What is the precision of float in C?

float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.

How accurate is float in C?

The precision of the float is 24 bits. There are 23 bits denoting the fraction after the binary point, plus there's also an "implicit leading bit", according to the online source. This gives 24 significant bits in total.

What is %s %d %F in C?

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].


1 Answers

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...

like image 105
Lindydancer Avatar answered Sep 18 '22 15:09

Lindydancer