Compare two double type variables within epsilon

 
public class Main {
  final static double EPSILON = 0.0000001;
  public static void main(String[] argv) {
    double da = 3 * .3333333333;
    double db = 0.99999992857;

    if (da == db) {
      System.out.println("Java considers " + da + "==" + db);
    } else if (equals(da, db, 0.0000001)) {
      System.out.println("True within epsilon " + EPSILON);
    } else {
      System.out.println(da + " != " + db);
    }

    double d1 = Double.NaN;
    double d2 = Double.NaN;
    if (d1 == d2)
      System.err.println("Comparing two NaNs incorrectly returns true.");
    if (!new Double(d1).equals(new Double(d2)))
      System.err.println("Double(NaN).equal(NaN) incorrectly returns false.");
  }

  public static boolean equals(double a, double b, double eps) {
    if (a==b) return true;
    return Math.abs(a - b) < eps;
  }
  public static boolean equals(double a, double b) {
    if (a==b) return true;
    return Math.abs(a - b) < EPSILON * Math.max(Math.abs(a), Math.abs(b));
  }
}
  

Output:


True within epsilon 1.0E-7
Home 
  Java Book 
    Runnable examples  

Data Type Double:
  1. Cast double to integer
  2. Create Double from double value
  3. Compare two double type variables within epsilon
  4. Compare double value arrays for almost equal
  5. Convert double to string
  6. Convert Double to numeric primitive data types
  7. Format double to percentage
  8. Is Double Infinite
  9. Is double positive infinity
  10. Is Double Not a Number(NaN)
  11. Round a double using BigDecimal
  12. Round double half up
  13. Min and Max value fo double type