Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check for NaN early when doing comparison #142

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,10 @@ public static boolean equalsIncludingNaN(float x, float y, float eps) {
* point values between {@code x} and {@code y}.
*/
public static boolean equals(final float x, final float y, final int maxUlps) {
if (Float.isNaN(x) || Float.isNaN(y)) {
return false;
}

final int xInt = Float.floatToRawIntBits(x);
final int yInt = Float.floatToRawIntBits(y);

Expand All @@ -238,8 +242,7 @@ public static boolean equals(final float x, final float y, final int maxUlps) {
// Numbers have same sign, there is no risk of overflow.
isEqual = Math.abs(xInt - yInt) <= maxUlps;
}

return isEqual && !Float.isNaN(x) && !Float.isNaN(y);
return isEqual;
}

/**
Expand Down Expand Up @@ -366,6 +369,10 @@ public static boolean equalsIncludingNaN(double x, double y, double eps) {
* point values between {@code x} and {@code y}.
*/
public static boolean equals(final double x, final double y, final int maxUlps) {
if (Double.isNaN(x) || Double.isNaN(y)) {
return false;
}

final long xInt = Double.doubleToRawLongBits(x);
final long yInt = Double.doubleToRawLongBits(y);

Expand All @@ -375,17 +382,12 @@ public static boolean equals(final double x, final double y, final int maxUlps)
final long deltaPlus = xInt & Long.MAX_VALUE;
final long deltaMinus = yInt & Long.MAX_VALUE;

// Note:
// If either value is NaN, the exponent bits are set to (2047L << 52) and the
// distance above 0.0 is always above an integer ULP error. So omit the test
// for NaN and return directly.

// Avoid possible overflow from adding the deltas by splitting the comparison
return deltaPlus <= maxUlps && deltaMinus <= (maxUlps - deltaPlus);
}

// Numbers have same sign, there is no risk of overflow.
return Math.abs(xInt - yInt) <= maxUlps && !Double.isNaN(x) && !Double.isNaN(y);
return Math.abs(xInt - yInt) <= maxUlps;
}

/**
Expand Down
Loading