Search This Blog

Thursday, January 8, 2009

C# NaN and IsNaN

Some mathematical operations yield results that are not real numbers. The answers may be imaginary numbers or undefined values, either of which cannot be represented within a floating-point structure. In these cases, the resultant value will be NaN.

"Not a Number"

C# and the .NET framework do not provide a manner of representing some numeric values. For example, there is no standard way for a variable to hold an imaginary number or complex number . Some of the mathematical methods of the Math class library can calculate such values or produce other answers that are not real numbers. Instead of producing an exception in these cases, the functions return a special value named NaN, which is an abbreviation of "Not a Number".

The NaN value can also be obtained from a constant field of the float or double structures. This field is a static member of the structure. It cannot be used for comparison purposes, as two NaN values could logically be different, so equality tests will always return false.

The following sample generates a NaN result by attempting to obtain the square root of a negative number. A comparison with the constant is then made. Note that the comparison fails.

double negSqrt = Math.Sqrt(-1); Console.WriteLine(negSqrt);                 // Outputs "NaN" Console.WriteLine(negSqrt == double.NaN);   // Outputs "False"

Testing for NaN

As standard comparison operators do not allow you to test if a value is not a number, the float and double structures provide a method for this purpose. The method, named IsNaN, returns a Boolean value that indicates if the provided parameter is a number or not.

double negSqrt = Math.Sqrt(-1); Console.WriteLine(double.IsNaN(negSqrt));   //Outputs "True"

No comments: