Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two NAN values in C++

Tags:

c++

compare

nan

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?

like image 790
CodeRider Avatar asked Mar 07 '13 10:03

CodeRider


People also ask

What causes NaN in C?

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.

How do I know if my float is NaN?

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.

What is INF in C?

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.

Is NaN a double in C++?

The nan() function in C++ returns a quiet NaN (Not-A-Number) value of type double.


2 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. 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.

like image 166
Joseph Mansfield Avatar answered Oct 13 '22 05:10

Joseph Mansfield


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.
like image 37
Bartek Banachewicz Avatar answered Oct 13 '22 06:10

Bartek Banachewicz