This is an issue when comparing a floating-point value to NaN using equality or inequality operators.
In most programming languages, floating-point numbers follow the IEEE 754 standard for arithmetic. This standard defines NaN (Not a
Number) as a special value that represents undefined or unrepresentable results, such as dividing zero by zero or taking the square root of a negative
number.
A critical aspect of IEEE 754 is that NaN is defined as never being equal to anything—not even to itself. This means:
NaN == NaN evaluates to falsex == NaN will always be false, regardless of the value of x, for both single-precision and
double-precision floating-point typesSimilarly, inequality comparisons are also unreliable:
x != NaN will always be true, even when x is actually NaNThis behavior makes equality tests for NaN fundamentally broken. Code that attempts to check whether a variable is NaN
using == or != will never work as intended, leading to incorrect program logic.
The correct approach is to use dedicated functions or methods specifically designed to test for NaN values (such as those typically
named isNaN or similar), which return accurate results.
When a program incorrectly tests for NaN (Not a Number) values using equality operators, the condition will never evaluate as expected. This leads to:
This affects the reliability and correctness of numerical computations.
Replace equality comparisons with NaN constants using the appropriate isNaN() method for the floating-point type you’re
working with.
double result = Math.sqrt(-1);
if (result == Double.NaN) { // Noncompliant
System.out.println("Invalid result");
}
double result = Math.sqrt(-1);
if (Double.isNaN(result)) {
System.out.println("Invalid result");
}