Possible Duplicate:
Retain precision with Doubles in java
Floating point inaccuracy examples
I know that there is a good reason pertaining to objects and the way doubles are stored in Java that makes this if statement false. My understanding is for some reason, it’s really 0.29999999 instead of .3. Could some one explain to me further and intuitively why this conditional returns false?
public class hello {
public static void main(String[] args) {
double a = 0.1;
double b = 0.1;
double c = 0.3;
if( a+b+a == c )
System.out.println("if is true");
}
}
You can use BigDecimal to see what the actual values are.
prints
As you can see,
doublecannot represent 0.1 precisely. When you print the value for 0.1 it does a small amount of rounding which hides the representation error. This is looks fine except when you perform an un-rounded calculation and you can see the representation error has accumulated.You can see that 0.1 * 3 results in an error which is large enough to be noticeable. However 0.1 + 0.3 works out to be the same as 0.4 (This is because the error for 0.1 is slightly too large and for 0.3 its slightly too small)