handle NaN and infinities correctly in the MathUtils.equals method with tolerance

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@746582 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Luc Maisonobe 2009-02-21 20:16:36 +00:00
parent c1b97f87d5
commit f1ee00c759
2 changed files with 13 additions and 6 deletions

View File

@ -373,6 +373,9 @@ public final class MathUtils {
/** /**
* Returns true iff both arguments are equal or within the range of allowed * Returns true iff both arguments are equal or within the range of allowed
* error (inclusive). * error (inclusive).
* <p>
* Two NaNs are considered equals, as are two infinities with same size.
* </p>
* *
* @param x first value * @param x first value
* @param y second 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 * @return true if the values are equal or within range of each other
*/ */
public static boolean equals(double x, double y, double eps) { 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);
} }
/** /**

View File

@ -336,11 +336,15 @@ public final class MathUtilsTest extends TestCase {
} }
public void testEqualsWithAllowedDelta() { public void testEqualsWithAllowedDelta() {
assertTrue(MathUtils.equals(153.0000, 153.0000, .0001)); assertTrue(MathUtils.equals(153.0000, 153.0000, .0625));
assertTrue(MathUtils.equals(153.0000, 153.0001, .0001)); assertTrue(MathUtils.equals(153.0000, 153.0625, .0625));
assertTrue(MathUtils.equals(152.9999, 153.0000, .0001)); assertTrue(MathUtils.equals(152.9375, 153.0000, .0625));
assertFalse(MathUtils.equals(153.0000, 153.0001, .00001)); assertTrue(MathUtils.equals(Double.NaN, Double.NaN, 1.0));
assertFalse(MathUtils.equals(152.9998, 153.0000, .0001)); 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() { public void testArrayEquals() {