Is a primitive double value equal to the dependence on the value?

I need to check if two double values ​​are equal, including magnitude and accuracy. I come across a strange scenario where a primitive double equal check is not consistent and depends on the value of the value.

The Java version I 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 is:

 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 
+3
java
source share
3 answers

What you are trying to do will not work for various boring and complex reasons that you can read about here: http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

If you are not going to compare the double representation of doubles (which may or may not be insightful), you will always need some kind of epsilon, that is, the margin of error when working with floating point numbers, Something like:

 boolean doublesAreEqual(double d1, double d2) { double d = d1 / d2; return (Math.abs(d - 1.0) < 0.00001 /* epsilon */); } 
+3
source share

Floating point numbers are approximations. They have a finite set of discrete values. When you create a floating point number by parsing a string, the maximum possible floating point value is selected to represent it.

The double closest to 15.9999999999999999 is 15.9999999999999999998, not 16.0, so the comparison is uneven. But 17.0 is the closest double to 16.9999999999999999, so they compare equals.

+1
source share

Do not use == when comparing double or float values.

use Double.compare http://download.oracle.com/javase/6/docs/api/java/lang/Double.html instead

and Float.compare for floats.

0
source share

All Articles