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
Java Book
Runnable examples
Data Type Double:
- Cast double to integer
- Create Double from double value
- Compare two double type variables within epsilon
- Compare double value arrays for almost equal
- Convert double to string
- Convert Double to numeric primitive data types
- Format double to percentage
- Is Double Infinite
- Is double positive infinity
- Is Double Not a Number(NaN)
- Round a double using BigDecimal
- Round double half up
- Min and Max value fo double type