How to produce a NaN float in c?
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/
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)
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.
From the GNU GCC manual math.h
defines macros that allow you to explicitly set a variable to infinity or NaN. Since this is a part of C99 you can use the following macros with other c99 compliant compilers i hope.
— Macro: float INFINITY An expression representing positive infinity. It is equal to the value produced by mathematical operations like 1.0 / 0.0. -INFINITY represents negative infinity.
You can test whether a floating-point value is infinite by comparing it to this macro. However, this is not recommended; you should use the isfinite macro instead. See Floating Point Classes.
This macro was introduced in the ISO C99 standard.
— Macro: float NAN An expression representing a value which is “not a number”. This macro is a GNU extension, available only on machines that support the “not a number” value—that is to say, on all machines that support IEEE floating point.
You can use ‘#ifdef NAN’ to test whether the machine supports NaN. (Of course, you must arrange for GNU extensions to be visible, such as by defining _GNU_SOURCE, and then you must include math.h.)
for further information you can see here: http://www.gnu.org/s/hello/manual/libc/Infinity-and-NaN.html