Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 586
Hossein Narimani Rad Avatar asked Jan 21 '13 19:01

Hossein Narimani Rad


People also ask

What is the NaN field for the system double structure?

IsNaN(Double) Method (System) Returns a value that indicates whether the specified value is not a number (NaN).

What is the value of double NaN?

In C#, the Double. NaN field represents a value that is not a number. It is constant.

What causes NaN in C#?

A method or operator returns NaN when the result of an operation is undefined. For example, the result of dividing zero by zero is NaN, as the following example shows. (But note that dividing a non-zero number by zero returns either PositiveInfinity or NegativeInfinity, depending on the sign of the divisor.)


1 Answers

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.

like image 87
timmyl Avatar answered Nov 03 '22 00:11

timmyl