Could anyone please me why the output of the following programme is not \" different different\"?
public static void main(String[] args)
{
float f1=3.2f;
fl
Because 3.2f is a float
value and 3.2
is a double
value. Floating point numbers are always slightly inaccurate because binary representation cannot implement them accurately, so comparing them for exact equality is a bad idea. Particularly comparing floats with doubles. Expressions such as 3.2f == 3.2f
are usually okay, but even those can fail in some languages, e.g. if they represent numbers in registers more accurately than in memory.
Because 3.2 is not representable exactly as floating point number and 6.5 is (hint: 6.5 = 13 * 2^(-1)), as well as the fact that 3.2 is a double
literal but 3.2f is a float
literal.
This can help understand
Also, I think anything with a decimal defaults into a double, so when you do a comparison, you have to add 'f' as well like if(f2==6.4f)
.
"3.2f" is a of type float. "3.2" is of type double.
6.5 has a finite binary representation: 110.1
Any floating type with at least 4 significant bits can represent this number perfectly.
110.100000000000000000000 (float)
= 6.5
110.10000000000000000000000000000000000000000000000000 (double)
= 6.5
3.2 on the other hand has an infinite binary representation: 101.0011001100110011...
float and double don't have infinite precision and thus can only approximate this number :(
101.001100110011001100110 (float)
= 3.2000000476837158203125
101.00110011001100110011001100110011001100110011001101 (double)
= 3.20000000000000017763568394002504646778106689453125
As you can clearly see, these numbers are not the same!