Why does NaN - NaN == 0.0 with the Intel C++ Compiler? Why does NaN - NaN == 0.0 with the Intel C++ Compiler? c c

Why does NaN - NaN == 0.0 with the Intel C++ Compiler?


The default floating point handling in Intel C++ compiler is /fp:fast, which handles NaN's unsafely (which also results in NaN == NaN being true for example). Try specifying /fp:strict or /fp:precise and see if that helps.


This . . . can't be right, right? My question: what do the relevant standards (ISO C, ISO C++, IEEE 754) say about this?

Petr Abdulin already answered why the compiler gives a 0.0 answer.

Here is what IEEE-754:2008 says:

(6.2 Operations with NaNs) "[...] For an operation with quiet NaN inputs, other than maximum and minimum operations, if a floating-point result is to be delivered the result shall be a quiet NaN which should be one of the input NaNs."

So the only valid result for the subtraction of two quiet NaN operand is a quiet NaN; any other result is not valid.

The C Standard says:

(C11, F.9.2 Expression transformations p1) "[...]

x − x → 0. 0 "The expressions x − x and 0. 0 are not equivalent if x is a NaN orinfinite"

(where here NaN denotes a quiet NaN as per F.2.1p1 "This specification does not define the behavior of signaling NaNs. It generally uses the term NaN to denote quiet NaNs")


Since I see an answer impugning the standards compliance of Intel's compiler, and no one else has mentioned this, I will point out that both GCC and Clang have a mode in which they do something quite similar. Their default behavior is IEEE-compliant —

$ g++ -O2 test.cc && ./a.out neg: -nansub: nan nan nanadd: nan nandiv: nan nan nanmul: nan nan$ clang++ -O2 test.cc && ./a.out neg: -nansub: -nan nan nanadd: nan nandiv: nan nan nanmul: nan nan

— but if you ask for speed at the expense of correctness, you get what you ask for —

$ g++ -O2 -ffast-math test.cc && ./a.out neg: -nansub: nan nan 0.000000add: nan nandiv: nan nan 1.000000mul: nan nan$ clang++ -O2 -ffast-math test.cc && ./a.out neg: -nansub: -nan nan 0.000000add: nan nandiv: nan nan nanmul: nan nan

I think it is entirely fair to criticize ICC's choice of default, but I would not read the entire Unix wars back into that decision.