user2239352
user2239352

Reputation: 301

How does float operations works in c? Big numbers weird results

The following code gives some odd results:

#include <stdio.h>
#include <float.h>

int main()
{
    float t = 1.0;  
    float res;
    float myFltMax = 340282346638528859.0;
    printf("FLT_MAX %f\n", FLT_MAX);

    res = FLT_MAX - t;
    printf("res %f\n", res);

    res = myFltMax - t;
    printf("res myFltMax %f\n", res);

    return 1;

}

The results are:

FLT_MAX 340282346638528859811704183484516925440.000000
res 340282346638528859811704183484516925440.000000
res myFltMax 340282356122255360.000000

So, if i subtract 1 from FLT_MAX the result is the same and if i subtract 1 from other big float, the result is greater than initial number.

I am using gcc version 4.7.2. Thank you.

Upvotes: 0

Views: 208

Answers (1)

Alexey Frunze
Alexey Frunze

Reputation: 62048

If you subtract 1 from myFltMax you don't get the difference greater than the initial number. You get the same number. Print myFltMax as well and you'll see that it's 340282356122255360 and not 340282346638528859.

Proof.

Basically, the compiler rounds your 340282346638528859 to the nearest value that can be represented in the floating point type and that happens to be 340282356122255360.

Upvotes: 3

Related Questions