Added equals and hash methods for comparing / hashing double values.

git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/math/trunk@141300 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Phil Steitz 2004-06-17 21:31:00 +00:00
parent 1363c7d014
commit 297d6c9d5b
2 changed files with 59 additions and 3 deletions

View File

@ -19,7 +19,7 @@ package org.apache.commons.math.util;
/**
* Some useful additions to the built-in functions in {@link Math}.
*
* @version $Revision: 1.17 $ $Date: 2004/05/19 14:16:32 $
* @version $Revision: 1.18 $ $Date: 2004/06/17 21:31:00 $
*/
public final class MathUtils {
@ -443,4 +443,27 @@ public final class MathUtils {
public static double sinh(double x) {
return (Math.exp(x) - Math.exp(-x)) / 2.0;
}
/**
* Returns an integer hash code representing the given double value.
*
* @param value the value to be hashed
* @return the hash code
*/
public static int hash(double value) {
long bits = Double.doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
/**
* Returns true iff both arguments are NaN or
* neither is NaN and they are equal
*
* @param x first value
* @param y second value
* @return true if the values are equal or both are NaN
*/
public static boolean equals(double x, double y) {
return ((Double.isNaN(x) && Double.isNaN(y)) || x == y);
}
}

View File

@ -22,7 +22,7 @@ import junit.framework.TestSuite;
/**
* Test cases for the MathUtils class.
*
* @version $Revision: 1.13 $ $Date: 2004/05/09 04:36:09 $
* @version $Revision: 1.14 $ $Date: 2004/06/17 21:31:00 $
*/
public final class MathUtilsTest extends TestCase {
@ -353,5 +353,38 @@ public final class MathUtilsTest extends TestCase {
public void testSinhNaN() {
assertTrue(Double.isNaN(MathUtils.sinh(Double.NaN)));
}
}
public void testEquals() {
double[] testArray = {Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d};
for (int i = 0; i < testArray.length; i++) {
for (int j = 0; j < testArray.length; j ++) {
if (i == j) {
assertTrue(MathUtils.equals(testArray[i], testArray[j]));
assertTrue(MathUtils.equals(testArray[j], testArray[i]));
} else {
assertTrue(!MathUtils.equals(testArray[i], testArray[j]));
assertTrue(!MathUtils.equals(testArray[j], testArray[i]));
}
}
}
}
public void testHash() {
double[] testArray = {Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d, 1E-14, (1 + 1E-14),
Double.MIN_VALUE, Double.MAX_VALUE};
for (int i = 0; i < testArray.length; i++) {
for (int j = 0; j < testArray.length; j ++) {
if (i == j) {
assertEquals(MathUtils.hash(testArray[i]), MathUtils.hash(testArray[j]));
assertEquals(MathUtils.hash(testArray[j]), MathUtils.hash(testArray[i]));
} else {
assertTrue(MathUtils.hash(testArray[i]) != MathUtils.hash(testArray[j]));
assertTrue(MathUtils.hash(testArray[j]) != MathUtils.hash(testArray[i]));
}
}
}
}
}