This is an issue when comparing a floating-point value to NaN using equality or inequality operators.

Why is this an issue?

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:

Similarly, inequality comparisons are also unreliable:

This 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.

What is the potential impact?

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.

How to fix it

Replace equality comparisons with NaN constants using the appropriate isNaN() method for the floating-point type you’re working with.

Code examples

Noncompliant code example

double result = Math.sqrt(-1);
if (result == Double.NaN) {  // Noncompliant
    System.out.println("Invalid result");
}

Compliant solution

double result = Math.sqrt(-1);
if (Double.isNaN(result)) {
    System.out.println("Invalid result");
}

Resources

Documentation

Related rules