I have to check to see whether two double values are equal including magnitude and precision. I encounter a weird scenario where primitive double equals check is not consistent and depend on magnitude of value.
Java version i’ve used:
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)
My code:
public class Test{
public static void main(String args[]) throws Exception{
String val1 = "15.999999999999999";
String val2 = "16";
String val3 = "16.999999999999999";
String val4 = "17";
double d1 = Double.parseDouble(val1);
double d2 = Double.parseDouble(val2);
double d3 = Double.parseDouble(val3);
double d4 = Double.parseDouble(val4);
System.out.println(val1 + "=" + val2 + "? ===>" + (d1==d2));
System.out.println(val3 + "=" + val4 + "? ===>" + (d3==d4));
}
}
Output:
15.999999999999999=16? ===>false
16.999999999999999=17? ===>true
What you’re trying to do won’t work for various boring and complicated reasons that you can read about here: http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
Unless you’re going to compare the bit-representation of the doubles (which may or may not be insightful), you will always need some sort of epsilon value, i.e. margin of error when dealing with floating-point representations of numbers. Something like: