Possible Duplicate:
Java floating point arithmetic
Hi All,
I was just reading a book and i came across this example which gave different outputs. Can somebody explain to me why.
public class Test {
public static void main(String[] args) {
double x = 0.3 - 0.2;
double y = 0.2 - 0.1;
System.out.println(x);
System.out.println(y);
System.out.println(y == x);
}
}
Output is :
0.09999999999999998
0.1
false
Computers represent floating-point numbers as an integer times a power of
2.0.1is not exactly representable as a floating point number (in the same way you can’t write1/3in decimal) and you therefore get rounding errors. The best way to avoid this is to use integer types when you can and to use a tolerant comparison function when you can’t. Do not compare floating point numbers for exact equality unless you know what you are doing.