Search code examples
cfloating-pointprecisionc99

In C how float or double type works exactly?


Now I am learning C at university. I fount an unexpected behavior in float type.

This is the example code:

#include <stdio.h>
int main(void) {
    float f = 100.0/3;
    printf("%.20f", f);
}

The true result is 33.3 (with 3 periodic). I also know that the machine can store only rational numbers and for me is ok, so the answars I expected may be:

  • 33.33333200000000000000 (just rounded)

at most

  • 33.33333400000000000000 (rounded up)
  • 33.33333200000000000000 (rounded down)
  • 33.33333000000000000000 (just truncated)

But after executing (compiled with GCC) the result is 33.33333206176757800000...

The numbers (061767578) after the 2 can't be explained in my mind.

Why this behaviour? I searched a lot, I found nothing :(


Solution

  • To see the exact value that is stored, you should print more than 20 digits. The number should end with 75000… or 25000….

    Assuming you are using an implementation of IEEE 754, each float is of the form num / den, where num has 24 binary(!) digits and den is a power of 2. (Except for denormalized numbers, but that's another topic.)