I was writing a sample program with floats but suddenly something weird happened. I would really appreciate if someone can shed some light on why I am facing such behavior from my program.
package Programs;
public class FloatTest {
/**
* @param args
*/
public static void main(String[] args) {
float f1 = (float) 3.2;
float f2 = (float) 6.5;
if (f1 == 3.2) {
System.out.println(f1 + " same");
} else {
System.out.println(f1 + " different");
}
if (f2 == 6.5) {
System.out.println(f2 + " same");
} else {
System.out.println(f2 + " different");
}
}
}
Output:
3.2 different
6.5 same
After doing some tests with changing values of f2 I noticed that I get unexpected result for f2 > 3.5 Why is that? Any input is really appreciated.
Thanks
I'm going to try my hand at a technical explanation for this. Since these values are being ultimately stored in the binary format, under some conditions precision will be lost.
6.5 should not lose any precision, as it can be converted to the binary value 110.1.
3.2, however, cannot be converted cleanly like this because the binary representation of .2 becomes irrational. It would be something along the lines of 11.00110011... This can only be, at best, rounded to 3.2 when converted the other way.
If somebody could verify what I'm saying, it would be fantastic - this is is based on an admittedly limited knowledge of how Java is handling this.
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