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;
float f2=6.5f;
if(f1==3.2)
System.out.println("same");
else
System.out.println("different");
if(f2==6.5)
System.out.println("same");
else
System.out.println("different");
}
o/p :different same
A floating point number, is a positive or negative whole number with a decimal point. For example, 5.5, 0.25, and -103.342 are all floating point numbers, while 91, and 0 are not.
'' If there is no minus zero, then 0.0 and -0.0 are both interpreted as simply a floating-point zero.
Integers and floats are two different kinds of numerical data. An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With