How to compare two NAN values ​​in C ++

I have an application in which a code area creates NAN values. I need to compare the values ​​for equality and based on this, execute the rest of the code. How to compare two NAN values ​​in C ++ for equality?

+8
c ++ compare nan
source share
3 answers

Assuming an IEEE 754 floating point representation, you cannot compare two NaN values ​​for equality. NaN is not equal to any value, including itself. However, you can check if they are NaN with the std::isnan <cmath> header:

 if (std::isnan(x) && std::isnan(y)) { // ... } 

This is only available in C ++ 11. Prior to C ++ 11, the Boost Math Toolkit provides some floating point classifiers . In addition, you can check if the value of NaN is by comparing it with itself:

 if (x != x && y != y) { // ... } 

Since NaN is the only value that is not equal to itself. Some compilers used to twist this before, but I'm not sure about the status at the moment (it works correctly with GCC).

MSVC provides the _isnan function.

The final alternative is to assume that you know this is an IEEE 754 representation and do some bit checking. Obviously, this is not the most portable option.

+17
source share

As for pre-C ++ 11, there will also be an increase for this .

 #include <boost/math/special_functions/fpclassify.hpp> template <class T> bool isnan(T t); // NaN. 
+3
source share

Any given NaN is not equal to anyone, it will never be equal to any other NaN, so comparing them with each other is a futile exercise.

From the GNU docs:

NaN is disordered: it is not equal, more or less than anything, including it. x == x is invalid if x is NaN. a source

+2
source share

All Articles