I stumbled upon .NET’s definition of double.NaN in code:
public const double NaN = (double)0.0 / (double)0.0;
This is done similarly in PositiveInfinity and NegativeInfinity.
double.IsNaN (with removing a few #pragmas and comments) is defined as:
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static bool IsNaN(double d)
{
if (d != d)
{
return true;
}
else
{
return false;
}
}
This is very counter-intuitive to me.
Why is NaN defined as division by zero? How is 0.0 / 0.0 represented “behind the scenes”? How can division by 0 be possible in double, and why does NaN != NaN?
Fairly simple answer here. .Net framework has implemented the floating point standard specified by the IEEE (
System.Doublecomplies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.). This is because floating point arithmetic actually has to work across many systems, not just x86/64 architectures, so by following the conventions this ensures that there will be less compatibility issues (for instance porting code from a DSP into an x86 processor).As for the d != d, this is a performance optimisation. Basically this instruction relies on a hardware instruction which can very quickly determine if two double floating point numbers are equal. Under the standard, NAN != NAN and therefore is the fastest way to test. Trying to find a reference for you.