PRODUCT : Borland C++ NUMBER : 1735 VERSION : All OS : All DATE : October 25, 1993 PAGE : 1/3 TITLE : Testing for Not a Number (NaN) /*************************************************************** TEST4NAN.C How to test for NaN (Not a Number) NaN is an IEEE standard constant which stands for Not a Number. It is returned if an invalid operation exception occurs within an operation. For example, sqrt(-1) will return a number with a bit configuration that is recognized as NaN because this operation would result in an imaginary number. NaN will be returned if the exponent of the resultant number contains all 1's and the mantissa does not consist of all 0's. The following is a code sample which demonstrates how to test for NaN. ***************************************************************/ #include #include #include struct LongDouble { unsigned char mant[8]; // the mantissa is the lower 8 bytes. unsigned int exp; // the exponent is the upper 2 bytes }; union Real // This union allows us to write in a long double and read out a // struct LongDouble. { struct LongDouble sld; long double ld; }; int IsNaN (long double x) // This function returns 1 if the parameter is any NaN type. A // float or double may be passed too, and the compiler will // promote them to long double so the test will still work. { PRODUCT : Borland C++ NUMBER : 1735 VERSION : All OS : All DATE : October 25, 1993 PAGE : 2/3 TITLE : Testing for Not a Number (NaN) union Real real; real.ld = x; if ((real.sld.exp &0x7FFF) == 0x7FFF) return 1; // ignore sign of exponent in // high bit of exponent. return 0; } int matherr (struct exception *a) // This function prevents the log function from complaining // about taking the log of a negative number. It simply // returns 1, preventing the default error message from being // printed. { return 1; } #pragma argsused int main (int argc, char *argv[]) { float f = 0.0; int j; for (j=7;j>-5;j-=2) { f = log (j); printf ("log of %d = ",j); if (IsNaN (f)) printf ("(Not a Number)\n"); else printf ("%f\n", f); } printf ("\n"); for (j=7;j>-5;j-=2) { f = sqrt (j); printf ("sqrt of %d = ",j); if (IsNaN (f)) printf ("(Not a Number)\n"); PRODUCT : Borland C++ NUMBER : 1735 VERSION : All OS : All DATE : October 25, 1993 PAGE : 3/3 TITLE : Testing for Not a Number (NaN) else printf ("%f\n", f); } return 0; } DISCLAIMER: You have the right to use this technical information subject to the terms of the No-Nonsense License Statement that you received with the Borland product to which this information pertains.