Search code examples
c#doublenaninfinityicomparable

CompareTo behaviour for double.NaN and double.NegativeInfinity


I was doing some statistical operations in C# (.Net 4) with double[] then i found some strange behavior with CompareTo method and double.NaN. when I try this code:

double.NaN.CompareTo(double.NegativeInfinity) //returns -1

It means double.NaN is even smaller than double.NegativeInfinity! can anyone explain why it is like this?


Solution

  • CompareTo does not tell you that one thing is smaller than another. It tells you one instance precedes (-), follows (+) or is interchangeable with (0) another instance when ordering instances.

    The why here is really up to those designing behavior for primitives in the CLR.

    IComparable's purpose is for ordering instances of a type. So for NaN, a valid double value, the decision was made to order it before any other instance of the type.

    Note that CompareTo is not necessarily the same, in meaning, or in intended use, as numeric greater than/less than operations. CompareTo is meant to provide an ordering over the set of values that double can take on. For example,

    double.NaN.CompareTo(double.NaN)
    

    will return 0. But

    double.NaN == double.NaN
    

    is false. Likewise,

    double.NaN.CompareTo(double.NegativeInfinity)
    

    returns -1, but

    double.NaN < double.NegativeInfinity
    

    returns false. So, the CompareTo method is not saying that mathematically double.NaN is smaller than double.NegativeInfinity. The less than operator in fact says that's not true. But it is saying that, when ordering values, double.NaN comes first.

    Here is a link to the Double type's LessThan Operator documentation as well. Reading that as well as the meaning of IComparable.CompareTo side by side should help clarify the difference in what the two methods are trying to express.