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 NAN values in C++ for equality?
NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can't be represented. It is used for floating-point operations. For example: The square root of negative numbers.
To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.
You can also type them directly into an expression or Edit table. Inf means infinity, and is the result of dividing a positive number by zero -- e.g., 1/0 → Inf. or computing a number larger than 1.796E308 (the largest number that your computer can represent in 64 bits) -- e.g. 1E307 * 100 → Inf.
The nan() function in C++ returns a quiet NaN (Not-A-Number) value of type double.
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 <cmath>
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.
Regarding pre-C++11, there's a boost for that, too.
#include <boost/math/special_functions/fpclassify.hpp>
template <class T>
bool isnan(T t); // NaN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With