Sub topic 11
Double equality: NaN and negative zero
This chapter covers the two special double values that break ordinary equality: NaN and negative zero. It assumes you know the following:
- Java's primitive types.
- The difference between
==andequalson objects. - How autoboxing converts between
doubleandDouble, which earlier chapters in this tutorial covered.
By the end you will be able to predict the result of every comparison between these values. You will also know which comparison to use in each situation.
Why doubles are different
Integer wrappers have one surprise: == on two Integer references compares identity, not value. Double has that surprise too. It also has a second one that has nothing to do with boxing. The primitive double follows the IEEE 754 floating-point standard, and that standard defines two values that behave oddly:
- NaN ("not a number") is the result of undefined operations such as
0.0 / 0.0orMath.sqrt(-1). - Negative zero (
-0.0) is a distinct bit pattern from0.0. It appears when you compute-1.0 * 0.0or write the literal-0.0.
The standard says NaN is unequal to everything, including itself. It also says 0.0 and -0.0 compare as equal. The Double class needs equals and hashCode to behave consistently, so it makes different choices and the two sets of rules disagree. Most of this chapter explains that disagreement.
The primitive rules
The ==, !=, <, >, <= and >= operators on primitive double follow IEEE 754:
public class PrimitiveRules {
public static void main(String[] args) {
double nan = Double.NaN;
double posZero = 0.0;
double negZero = -0.0;
System.out.println(nan == nan); // false
System.out.println(nan != nan); // true
System.out.println(nan < 1.0); // false
System.out.println(nan > 1.0); // false
System.out.println(Double.isNaN(nan)); // true
System.out.println(posZero == negZero); // true
System.out.println(posZero < negZero); // false
System.out.println(1 / posZero); // Infinity
System.out.println(1 / negZero); // -Infinity
}
}Every ordered comparison involving NaN is false. nan != nan is the only comparison that is true. Because of this, the test x == Double.NaN can never succeed, so always call Double.isNaN(x). The same applies to Float.isNaN.
Negative zero is invisible to the comparison operators, but division exposes it. Dividing by 0.0 gives positive infinity and dividing by -0.0 gives negative infinity. Printing the value also shows the sign: System.out.println(-0.0) prints -0.0.
The wrapper rules
Double.equals does not use the == operator on the underlying values. Its documentation says two Double objects are equal when Double.doubleToLongBits gives the same long for both. This turns both rules around:
public class WrapperRules {
public static void main(String[] args) {
Double boxedNan = Double.NaN;
System.out.println(boxedNan.equals(Double.NaN)); // true
Double posZero = 0.0;
System.out.println(posZero.equals(-0.0)); // false
System.out.println(posZero.equals(0.0)); // true
System.out.println(Double.valueOf(1.0).equals(1)); // false
}
}The last line catches many people. The argument 1 is an int, and equals(Object) takes an object, so the compiler boxes it to an Integer. A Double is never equal to an Integer, whatever their numeric values. Write equals(1.0) if you mean a double.
Here is the full comparison:
| Expression | Result | Reason |
|---|---|---|
| `Double.NaN == Double.NaN` | `false` | IEEE 754 numeric comparison |
| `Double.valueOf(Double.NaN).equals(Double.NaN)` | `true` | same bits after `doubleToLongBits` |
| `0.0 == -0.0` | `true` | IEEE 754 numeric comparison |
| `Double.valueOf(0.0).equals(-0.0)` | `false` | different sign bit |
| `Double.compare(0.0, -0.0)` | `1` | total order puts `-0.0` before `0.0` |
| `Double.compare(Double.NaN, Double.NaN)` | `0` | `NaN` equals itself in the total order |
Mixed comparisons: when `==` is numeric and when it is identity
Whether == compares numbers or references depends on the static types of the operands:
- Both operands are primitive
double: numeric comparison. - One operand is
doubleand the other isDouble: theDoubleis unboxed, then compared numerically. - Both operands are
Double: reference comparison.
public class MixedComparisons {
public static void main(String[] args) {
Double a = Double.NaN;
Double b = Double.NaN;
System.out.println(a == Double.NaN); // false: unboxed, numeric, NaN != NaN
System.out.println(a == b); // false: two references (and never cached)
System.out.println(a.equals(b)); // true
Double x = 2.5;
Double y = 2.5;
System.out.println(x == y); // false in practice: valueOf allocates a new Double
System.out.println(x.equals(y)); // true
}
}Unlike Integer.valueOf, which must cache small values, Double.valueOf has no caching guarantee. In practice each call allocates a new object. This means x == y on Double references is false even for tiny, ordinary values like 2.5. Do not write code that depends on either outcome.
A total order for sorting and collections
Sorting needs a consistent total order, where every pair of values can be ranked. The IEEE rules do not give one, because NaN is neither less than, greater than, nor equal to anything. Double.compare and Double.compareTo supply a total order with two extra rules:
-0.0is less than0.0.NaNis greater than every other value, including positive infinity, and equal to itself.
import java.util.Arrays;
public class TotalOrder {
public static void main(String[] args) {
System.out.println(Double.compare(0.0, -0.0)); // 1
System.out.println(Double.compare(Double.NaN, Double.POSITIVE_INFINITY)); // 1
System.out.println(Double.compare(Double.NaN, Double.NaN)); // 0
double[] values = {3.0, Double.NaN, 0.0, -0.0, -1.5, Double.POSITIVE_INFINITY};
Arrays.sort(values);
System.out.println(Arrays.toString(values));
// [-1.5, -0.0, 0.0, 3.0, Infinity, NaN]
}
}Arrays.sort(double[]) uses the same order, so NaN values end up at the end of the array and -0.0 sits just before 0.0. If sorting used < directly, a NaN in the middle would make the result unpredictable.
Choose the comparison by what you are trying to do:
Effects on collections and records
Because collections use equals and hashCode, they follow the wrapper rules, not the primitive ones. Double.hashCode is computed from the same bits that equals compares, so the two are consistent.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CollectionEffects {
static int indexOf(double[] data, double target) {
for (int i = 0; i < data.length; i++) {
if (data[i] == target) { // never true when target is NaN
return i;
}
}
return -1;
}
public static void main(String[] args) {
List<Double> list = new ArrayList<>(List.of(1.0, Double.NaN));
System.out.println(list.contains(Double.NaN)); // true
System.out.println(list.indexOf(Double.NaN)); // 1
double[] array = {1.0, Double.NaN};
System.out.println(indexOf(array, Double.NaN)); // -1
Set<Double> set = new HashSet<>();
set.add(0.0);
set.add(-0.0);
set.add(Double.NaN);
set.add(Double.NaN);
System.out.println(set.size()); // 3
}
}The same value is found in the List<Double> and missed in the hand-written array loop. The set holds both zeros as separate elements, but only one NaN. This is often a surprise in code that deduplicates measurements, because two zeros that look identical in output are stored twice.
Other library code follows the wrapper rules too. Objects.equals calls equals. Arrays.equals(double[], double[]) compares elements with the same bit-based test, so two arrays that both contain NaN at the same position are equal. Record classes also compare double components with Double.compare, so two records holding NaN are equal.
Math.min, Math.max and detecting negative zero
Math.min and Math.max follow the total-order rules for zeros and propagate NaN:
public class MinMaxAndZero {
static boolean isNegativeZero(double x) {
return Double.doubleToRawLongBits(x) == Long.MIN_VALUE;
}
public static void main(String[] args) {
System.out.println(Math.min(0.0, -0.0)); // -0.0
System.out.println(Math.max(-0.0, 0.0)); // 0.0
System.out.println(Math.min(1.0, Double.NaN)); // NaN
System.out.println(isNegativeZero(-0.0)); // true
System.out.println(isNegativeZero(0.0)); // false
System.out.println(-0.0 == 0.0); // true, so == cannot detect it
double sum = 0.0 + -0.0;
System.out.println(sum); // 0.0
double product = -1.0 * 0.0;
System.out.println(product); // -0.0
}
}Math.min returns -0.0 for the pair of zeros, and any NaN argument produces NaN. A common bug is a "running minimum" loop that uses if (v < min). That loop silently ignores NaN values, while Math.min would let one poison the result. Decide which behavior you want and filter NaN explicitly if needed.
Negative zero can only be detected through its bits or through a division. Double.doubleToRawLongBits(-0.0) equals Long.MIN_VALUE, because only the sign bit is set.
NaN has many bit patterns
IEEE 754 allows many bit patterns for NaN. Java's Double.NaN is the canonical quiet NaN, 0x7ff8000000000000L, but arithmetic or Double.longBitsToDouble can produce others. equals hides the difference, because doubleToLongBits collapses every NaN into the canonical one. doubleToRawLongBits does not.
public class NanPatterns {
public static void main(String[] args) {
double other = Double.longBitsToDouble(0x7ff8000000000123L);
System.out.println(Double.isNaN(other)); // true
System.out.println(Double.valueOf(other).equals(Double.NaN)); // true
System.out.println(Double.doubleToLongBits(other) == Double.doubleToLongBits(Double.NaN)); // true
System.out.println(Double.doubleToRawLongBits(other) == Double.doubleToRawLongBits(Double.NaN)); // false
}
}You rarely need the raw form. Use it only when you are serializing exact bits or writing a binary protocol, and note that code which stores raw bits will see two NaN values as different.
Common mistakes
- Writing
x == Double.NaN. It is always false. UseDouble.isNaN(x). - Expecting
Double.equalsto match==. It differs forNaN(equal) and for the two zeros (not equal). - Calling
Double.equalswith anintorIntegerargument. The result is always false. - Using
==on twoDoublereferences and expecting a value comparison. - Using
<in a hand-written minimum or sort.NaNis skipped or breaks the ordering. UseMath.minorDouble.compare. - Treating
0.0and-0.0as one key in aHashMap<Double, V>. They are two different keys.
Exercise
What do these three expressions print, and why? (1) Double.valueOf(0.0).equals(-0.0), (2) 0.0 == -0.0, (3) Double.compare(0.0, -0.0).
Show answer
(1) prints false, because equals compares the bit patterns from doubleToLongBits, and the sign bits differ. (2) prints true, because the primitive == follows IEEE 754, which treats the two zeros as equal. (3) prints 1, because Double.compare uses a total order in which -0.0 is less than 0.0, so 0.0 is greater.
Exercise
A method receives a List<Double> of sensor readings that may contain NaN. A teammate wrote readings.stream().filter(r -> r != Double.NaN).count() to count valid readings, but it counts every reading. Why does it fail, and how do you fix it?
Show answer
The lambda parameter r is a Double and Double.NaN is a primitive double, so r is unboxed and compared numerically. NaN != NaN is always true, so nothing is filtered out. The fix is filter(r -> !Double.isNaN(r)). The call unboxes r and tests it correctly. If a reading could also be null, filter out nulls first, because unboxing null throws NullPointerException.