what does NaN mean for doubles?

  • Infinity is a mathematical construct:

    For instance, In euclidean space, the division through the null-element (zero in that case) should yield Infinity:

    1 / 0 = Infinity
    
  • Not a Number or NaN is a computational construct, that came along with parsers and programmatic limitations, and its output can be assigned different meaning depending on the function in question.

    For instance, a result may only be mathematically tractable using a different number system, which is easy for a mathematician to do, but in your function you may be left as the only pragmatic option to return NaN. Consider, the square root of -1:

    sqrt(-1) = NaN
    

    ...an operation which is easily tractable in complex and phase space.

Experiment:

Open up the JavaScript.Console (CTRL+SHIFT+J) in your browser, and type

>>> Math.sqrt(-1)
NaN

>>> 1/0
Infinity

>>> Number.MAX_VALUE
1.7976931348623157e+308

>>> Number.MAX_VALUE *2
Infinity

>>> parseFloat("I am not a Number")
NaN

In C# the typical 'NaN-situations' are mostly handled through Exceptions:

csharp> Int64.MaxValue;
9223372036854775807
csharp> Int64 i_64 = Int64.MaxValue;
//the number will overflow into the sign-bit
csharp> i_64 +=1;
//...or similarly with Doubles...
csharp> Double.MaxValue;
1.79769313486232E+308

//following, an exception is thrown before overflowing
csharp> Int64 i_64 = Int64.MaxValue+1;
{interactive}(1,29): error CS0220: The operation overflows at compile time in ch
ecked mode

Dynamic typed languages:

Overall, the usage of NaN is somewhat flexibly assigned in different programming languages. Using NaN at the loss of some 'contextual information', is convenient in dynamically typed scripting languages, where programmers generally do not want to bother with complex exception-types and handling thereof.


From Wikipedia :

In computing, NaN (Not a Number) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations. Systematic use of NaNs was introduced by the IEEE 754 floating-point standard in 1985, along with the representation of other non-finite quantities like infinities.

And from MSDN :

  • Represents a value that is not a number (NaN). This field is constant.

  • The value of this constant is the result of dividing zero by zero.

  • This constant is returned when the result of an operation is undefined.

  • Use IsNaN to determine whether a value is not a number. It is not possible to determine whether a value is not a number by comparing it to another value equal to NaN.

Where as Infinity (positive infinity and negative infinity) is the result of a floating point operation that causes an overflow (For example 3.0 / 0).


check whether double has value, if not then return 0

if (double.Equals(double.NaN, myValue))
    myValue= 0;

Usually happens when you divide 0 by 0. Read more here: http://msdn.microsoft.com/en-us/library/system.double.nan.aspx