How to produce a NaN float in c?
float f = (float)'a';
if(f < 0){
}
else if(f == 0){
}
else if(f > 0){
}
else{
printf("NaN\n");
}
f
won't be greater/equal/less than 0
if it's a NaN
.
But how to produce such a f
in the first place?
I tried various ways to produce a NaN
,but none work..
Using floating point numbers, 0.0 / 0.0
isn't a "divide by zero" error; it results in NaN
.
This C program prints -nan
:
#include <stdio.h>
int main()
{
float x = 0.0 / 0.0;
printf("%f\n", x);
return 0;
}
In terms what NaN
looks like to the computer, two "invalid" numbers are reserved for "signaling" and "quiet" NaN (similar to the two invalid numbers reserved for positive and negative infinity). The Wikipedia entry has more details about how NaN is represented as an IEE floating point number.
To produce a nan, there are a few ways:
1) generate it manually (read ieee754
to set up the bits properly)
2) use a macro. GCC exposes a macro NAN
. It's defined in math.h
The general way to check for a nan is to check if (f == f)
(which should fail for nan values)
For nan, the exponent bits in the float representation should all be set to 1 (float consists of a signed bit, a set of exponent bits and a set of mantissa bits)
You can either use NAN
macro, or simply one of nan/nanf
functions to assign a nan value to a variable.
to check if you are dealing with a nan value, you can use isnan()
.
Here is an example:
#include <stdio.h>
#include <math.h>
int main(void) {
float a = NAN;//using the macro in math.h
float f = nanf("");//using the function version
double d = nan("");//same as above but for doubles!
printf("a = %f\nf = %f\nd = %f\n",a,f,d);
if(isnan(a))
puts("a is a not a number!(NAN)\n");
return 0;
}
Running the code snippet above will give you this output:
a = nan
f = nan
d = nan
a is a not a number!(NAN)
Run the code yourself : http://ideone.com/WWZBl8
read more information : http://www.cplusplus.com/reference/cmath/NAN/