How the precision for floating point numbers 0.1 and 0.5 varies in c

I have attached two programs. I got the programs from a web portal. Could you tell the explanation for the same?

Program 1:

int main()
{
float x = 0.4;
if (x == 0.4)
printf("\n if");
printf("\n sizeof(0.4) : %d sizeof(x) : %d",sizeof(0.4) , sizeof(x));
return 0;
}

Program 2:

int main()
{
float x = 0.5;
if (x == 0.5)
printf("\n if") ;
printf("\n sizeof(0.5) : %d sizeof(x) : %d",sizeof(0.5) , sizeof(x));
return 0;
}

For Program 1, I got the output as:
sizeof(0.4) : 8 sizeof(x) :4

For Program 2, I got the output as:
if
sizeof(0.5) : 8 sizeof(x) :4

What is the difference between these two programs executions?

The compiler considers any decimal constant value as double by default, if not mentioned explicitly.
Check out this code below:

printf("%d",sizeof(float(0.5))); [ This is explicit type conversion,converting double to float]

printf("\n");

It gives output as 4.

If no data type is there it is simply treated as double and gives the output as 8.


float c;
sizeof(c) is 4 because it is declared as float, defined by user.

The size of float is 4.

1 Like

First of all you should know that 0.4 and 0.5 are double constants while 0.4f and 0.5f are floating point constants. Size of a double is 8 bytes and size of a float is 4 bytes. This explains the second part of the question; sizeof(x) is 4 bytes and sizeof(0.4),sizeof(0.5) is 8 bytes.

Now for the first part, 0.5 has an exact binary representation (0.1) while 0.4 does not have an exact binary representation (0.011001100110…). As the double constant has a higher precision than floating point constant (8 bytes vs 4 bytes, so more number of bits can be stored which makes it closer to actual value), 0.5f is equal to 0.5 but 0.4f is less than 0.4. This explains the first part of the question, because x==0.5 is true while x==0.4 is false.

Hope you understood the point :slight_smile:

2 Likes

no difference between the two except the value of x…
0.4 and 0.5 are double constants while x in p1 and p2 are floating point constants,
since at the time of initialization x=0.4; 0.4 which is double are auto converted into 0.4f and stored in x ,now we know that sizeof give size of variable or constant u r quoted for thats all…

1 Like

Comparison of floating point numbers is not accurate.
For comparison with floating point numbers, we need to improvise a bit, depending on the problem.
Take a look at these links:

http://floating-point-gui.de/errors/comparison/

http://how-to.wikia.com/wiki/Howto_compare_floating_point_numbers_in_the_C_programming_language