Why is this happening?

Code 1:
#include<stdio.h>
void main()
{
double a=1.1;
float b=1.1;
if(b==(float)a)
printf(“Earth”);
else
printf(“Mars”);
}
OUTPUT: Earth

Code 2:
#include<stdio.h>
void main()
{
double a=1.1;
float b=1.1;
if((double)b==a)
printf(“Earth”);
else
printf(“Mars”);
}
OUTPUT: Mars

Why are the outputs different?

The important factors under consideration with float or double numbers are:

Precision & Rounding

Precision:

The precision of a floating point number is how many digits it can represent without losing any information it contains.

Consider the fraction 1/3. The decimal representation of this number is 0.33333333333333… with 3′s going out to infinity. An infinite length number would require infinite memory to be depicted with exact precision, but float or double data types typically only have 4 or 8 bytes. Thus Floating point & double numbers can only store a certain number of digits, and the rest are bound to get lost. Thus, there is no definite accurate way of representing float or double numbers with numbers that require more precision than the variables can hold.

Rounding:

There is a non-obvious differences between binary and decimal (base 10) numbers.
Consider the fraction 1/10. In decimal, this can be easily represented as 0.1, and 0.1 can be thought of as an easily representable number. However, in binary, 0.1 is represented by the infinite sequence: 0.00011001100110011…

#include < iomanip >
#include < iostream >


int main()
{
  std::cout << std::setprecision(100) << (double)1.1 << std::endl;
  std::cout << std::setprecision(100) << (float)1.1 << std::endl;
  std::cout << std::setprecision(100) << (double)((float)1.1) << std::endl;
}

Output :

1.100000000000000088817841970012523233890533447265625

1.10000002384185791015625

1.10000002384185791015625

Neither float nor double can represent 1.1 accurately. When you try to do the comparison the float number is implicitly up-converted to a double. The double data type can accurately represent the contents of the float, so the comparison yields false.

For more information/clearification, go through this and this awesome links and also this and this at SO.

Button line : NEVER COMPARE FLOAT WITH FLOAT , FLOAT WITH DOUBLE, DOUBLE WITH DOUBLE STRAIGHTWAY. Use some other techniques instead.

1 Like