C NAN Number
Are you know how to create NAN number (Not a Number) in C? If you use Matlab, you can create NAN number by fill value variable with nan value (example : a=nan). What the the meaning of NAN number? NaN (Not a Number) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations (from wikipedia). We can create NAN number by :
- The divisions 0/0 and ±∞/±∞
- The multiplications 0×±∞ and ±∞×0
- The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions
- etc
When use C, I want to create NAN number or to check NAN number. So, I create a simple C code to create NAN number and to check a number is NAN or not. Create new file and save with name ceknan.c. Copy this code to that file.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(int argc, char **argv)
{
float a, b, c,d ;
int ceknan;
a = NAN; //create nan number
c = sqrt(-1); //create nan number
b = 10; //create real number
d = a-b; //create nan number
printf("print number\n");
printf("a=%f b=%f c=%f d=%f\n", a,b,c,d);
printf("\ncheck nan number \n");
printf("use isnan(x), a is nan =%i, b is nan =%i \n", isnan(a), isnan(b));
printf("\ncompare value of x to check number is nan or not \n");
if(a==a) ceknan = 0;
else ceknan = 1;
printf("a is nan = %i \n", ceknan);
if(b==b) ceknan = 0;
else ceknan = 1;
printf("b is nan = %i \n", ceknan);
return(1);
}
Compile this C Check NAN Number code in terminal with command :
gcc ceknan.c -o ceknan -lm
This is output from this C Check NAN Number program :
toto@andLinux:~/workspace$ ./ceknan print number a=nan b=10.000000 c=nan d=nan check nan number use isnan(x), a is nan =1, b is nan =0 compare value of x to check number is nan or not a is nan = 1 b is nan = 0
I use isnan function (function from C check NAN number is nan or not) and use variable compared function. So, if you want to check NAN number in C, you can use isnan function or compared a variable with itself. If that variable not equal with that variable itself. So, we can conclude that number is NAN.