001 package org.expasy.jpl.commons.base.math;
002
003
004 import java.util.Comparator;
005
006
007 // Floating point precision problems :
008 // real literals are approximated in memory.
009 // i.e :
010 // ! double tol = 0.1
011 // ! System.out.println(tol);
012 // Display : 0.10000000000000009
013 // Here, the approximation failed at 17th digit
014 // after decimal point :
015 // here the fractionary number is : 100100100100100...
016 // leading to an unavoidable truncation
017 public final class DoubleComparator implements Comparator<Double> {
018
019 public static final double DEFAULT_EPSILON = 0.00001;
020
021 public static final DoubleComparator INSTANCE =
022 new DoubleComparator(DEFAULT_EPSILON);
023
024 private double epsilon;
025
026 private DoubleComparator(double epsilon) {
027 this.epsilon = epsilon;
028 }
029
030 public static DoubleComparator newInstance(double epsilon) {
031 return new DoubleComparator(epsilon);
032 }
033
034 public static DoubleComparator getDefaultInstance() {
035 return INSTANCE;
036 }
037
038 @Override
039 public int compare(Double d1, Double d2) {
040 double delta = d1.doubleValue() - d2.doubleValue();
041
042 if (Math.abs(delta) <= epsilon) {
043 return 0;
044 } else {
045 return (int) Math.signum(delta);
046 }
047 }
048
049 }