How to compare two NAN values in C++

前端 未结 3 1548
离开以前
离开以前 2020-12-18 23:57

I have an application in which a code area produces NAN values. I have to compare the values for equality and based on that execute the rest of the code.How to compare two N

3条回答
  •  春和景丽
    2020-12-19 00:18

    Assuming an IEEE 754 floating point representation, you cannot compare two NaN values for equality. NaN is not equal to any value, including itself. You can however test if they are both NaN with std::isnan from the header:

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

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

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

    Since NaN is the only value that is not equal to itself. In the past, certain compilers screwed this up, but I'm not sure of the status at the moment (it appears to work correctly with GCC).

    MSVC provides a _isnan function.

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

提交回复
热议问题