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.
Joseph mansfield
source share