Testing if Float value is NaN
Solution 1
The problem is maybe in your initialization (at least that explains the value you see in gdb) :
FLOAT32 test_NaN = 0x414570A3;
The hex value given is considered as an integer and converted to float (with exponent and value) meaning it is stored in a different format.
If you want to force the bits inside the float, then you need to memcpy:
FLOAT32 test_NaN;
memcpy(&test_NaN, 0x414570A3, 4);
Solution 2
Include math.h
and use int isnan(x)
. Don't forget to link with -lm
Solution 3
If <math.h>
is not available, then do this:
if (x != x)
{
// x is NaN
}
kp11
Updated on October 13, 2020Comments
-
kp11 over 3 years
Possible Duplicate:
Checking if a double (or float) isnan
in C++I have a requirement to check if float is
NaN
. By going through some of the links I found the most common check.FLOAT32 f32_test_NaN = (some_value); if (f32_test_NaN == f32_test_NaN) { //do something; } else { // do something; }
But this does not seem to work for me. My code is as follows:
FLOAT32 test_NaN = 0x414570A3;//some value - is this ok?
Debugging on GDB:
(gdb) p test_NaN $1 = 1.09506982e+09 (gdb) p/x test_NaN $2 = 0x41457080 // Hex is not same as init value - What is compiler doing?
So in my case
test_NaN
is equal totest_NaN
.Please let me know if any compiler setting has to be done. I am running on solaris. Or is there any other way to check the same.
Thanks in advance.