ks1322
ks1322

Reputation: 35708

Can I print exactly representable float without loss of precision?

I am trying to print float value 299792450 with the following code:

#include <stdio.h>

int main()
{
    printf("%f\n", 299792450.0f);
    return 0;
}

According to IEEE 754 Calculator, this is exactly representable floating point value in binary32 format. However I am getting another value in output:

$ ./a.out 
299792448.000000

Why it is not equal to 299792450? I expected it to be 299792450 because it is exactly representable and there should be no loss of precision.

Upvotes: 2

Views: 493

Answers (3)

tadman
tadman

Reputation: 211540

A float value doesn't have enough precision for a value like this, you need to use a double or, for maximum precision, a long double:

#include <stdio.h>

int main()
{
    printf("%Lf\n", 299792450.0L);
    return 0;
}

Upvotes: 1

chux
chux

Reputation: 153303

The IEEE 754 Calculator, even in "binary32" mode, reports values as rounded decimal values, not exact values.

"this is exactly representable floating point value in binary32 format. " is unfounded.

Aside: code to print a FP exactly

Upvotes: 4

dbush
dbush

Reputation: 223689

Assuming a float is a IEEE754 single precision floating point number, 299792450 cannot be represented exactly.

This value requires at least 28 bits of precision, but a float has at most 24 bits of precision. So the value gets rounded to the closest possible value that can be represented.

If you used a double which has 53 bits of precision, you would see the exact value.

printf("%f\n", 299792450.0);

Upvotes: 5

Related Questions