Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a double (or float) is NaN in C++

Tags:

c++

double

nan

Is there an isnan() function?

PS.: I'm in MinGW (if that makes a difference).

I had this solved by using isnan() from <math.h>, which doesn't exist in <cmath>, which I was #includeing at first.

like image 216
hasen Avatar asked Feb 20 '09 18:02

hasen


People also ask

Can a float be NaN?

NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis.

Is NaN in C?

The NaN values are used to identify undefined or non-representable values for floating-point elements, such as the square root of negative numbers or the result of 0/0. In C, this is implemented as a macro that returns an int value.

Can primitive double Be NaN?

Sure! NaN is a static constant in the Float and Double classes.

Is NaN a double in C++?

The nan() function in C++ returns a quiet NaN (Not-A-Number) value of type double. The function is defined in <cmath> header file.


1 Answers

According to the IEEE standard, NaN values have the odd property that comparisons involving them are always false. That is, for a float f, f != f will be true only if f is NaN.

Note that, as some comments below have pointed out, not all compilers respect this when optimizing code.

For any compiler which claims to use IEEE floating point, this trick should work. But I can't guarantee that it will work in practice. Check with your compiler, if in doubt.

like image 60
jalf Avatar answered Sep 22 '22 03:09

jalf