diff --git a/src/java/org/apache/commons/math/util/MathUtils.java b/src/java/org/apache/commons/math/util/MathUtils.java index 3e3a6fdef..a03f4b85d 100644 --- a/src/java/org/apache/commons/math/util/MathUtils.java +++ b/src/java/org/apache/commons/math/util/MathUtils.java @@ -373,6 +373,9 @@ public final class MathUtils { /** * Returns true iff both arguments are equal or within the range of allowed * error (inclusive). + *

+ * Two NaNs are considered equals, as are two infinities with same size. + *

* * @param x first value * @param y second value @@ -380,7 +383,7 @@ public final class MathUtils { * @return true if the values are equal or within range of each other */ public static boolean equals(double x, double y, double eps) { - return x == y || (x < y && (x + eps) >= y) || (x > y && x <= (y + eps)); + return equals(x, y) || (Math.abs(y - x) <= eps); } /** diff --git a/src/test/org/apache/commons/math/util/MathUtilsTest.java b/src/test/org/apache/commons/math/util/MathUtilsTest.java index 20b61df09..6e75859a9 100644 --- a/src/test/org/apache/commons/math/util/MathUtilsTest.java +++ b/src/test/org/apache/commons/math/util/MathUtilsTest.java @@ -336,11 +336,15 @@ public final class MathUtilsTest extends TestCase { } public void testEqualsWithAllowedDelta() { - assertTrue(MathUtils.equals(153.0000, 153.0000, .0001)); - assertTrue(MathUtils.equals(153.0000, 153.0001, .0001)); - assertTrue(MathUtils.equals(152.9999, 153.0000, .0001)); - assertFalse(MathUtils.equals(153.0000, 153.0001, .00001)); - assertFalse(MathUtils.equals(152.9998, 153.0000, .0001)); + assertTrue(MathUtils.equals(153.0000, 153.0000, .0625)); + assertTrue(MathUtils.equals(153.0000, 153.0625, .0625)); + assertTrue(MathUtils.equals(152.9375, 153.0000, .0625)); + assertTrue(MathUtils.equals(Double.NaN, Double.NaN, 1.0)); + assertTrue(MathUtils.equals(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); + assertTrue(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1.0)); + assertFalse(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); + assertFalse(MathUtils.equals(153.0000, 153.0625, .0624)); + assertFalse(MathUtils.equals(152.9374, 153.0000, .0625)); } public void testArrayEquals() {