Double NaN Never Equals Itself
NaN compares false against everything including itself: use Double.isNaN for detection and Double.compare for ordering, which treats NaN as equal to itself.
Code
public class NanIdentity {
public static void main(String[] args) {
double nan = Double.NaN;
// NaN 与任何值(包括自己)的 == 比较都是 false
System.out.println("nan == nan : " + (nan == nan));
System.out.println("nan == 1.0 : " + (nan == 1.0));
// 判等用 isNaN;排序/查找用 Double.compare,它把 NaN 视为彼此相等
System.out.println("Double.isNaN : " + Double.isNaN(nan));
System.out.println("Double.compare: " + Double.compare(nan, nan));
// 0.0/0.0 与负数开方都产生 NaN;compare 还能区分 0.0 与 -0.0
double sqrtNeg = Math.sqrt(-1);
System.out.println("sqrt(-1) NaN : " + Double.isNaN(sqrtNeg));
System.out.println("0.0 vs -0.0 : " + Double.compare(0.0, -0.0));
}
}The code in one pass
Everything happens inside the class NanIdentity and the function main.
Points of care
- Runs on what the toolchain already provides — nothing extra.
Putting it to use
The operative signature: public static void main(String[] args)
The run emits 6 labeled sections — nan == nan :, nan == 1.0 :, Double.isNaN :, Double.compare:, sqrt(-1) NaN :, 0.0 vs -0.0 : — one per step.
Core lines
double sqrtNeg = Math.sqrt(-1);
double nan = Double.NaN;
Interactive Tools for This Topic
FAQ
- What does Double NaN Never Equals Itself print when run?
- Invoke the file as-is — the `nan == nan :`, `nan == 1.0 :`, `Double.isNaN :` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.