开发者

Why float.NaN != double.NaN in C#?

Why float.NaN != double.NaN ?

while float.PositiveInfinity == double.PositiveInfinity and float.NegativeInfinity == double.NegativeInfinity are equal.

EXAMPLE:

bool PosInfinity = (float.Posit开发者_StackOverflow社区iveInfinity == double.PositiveInfinity); //true
bool NegInfinity = (float.NegativeInfinity == double.NegativeInfinity); //true

bool isNanEqual = (float.NaN == double.NaN);  //false, WHY?


NaN is never equal to NaN (even within the same type). Hence why the IsNaN function exists:

Double zero = 0;
// This will return true.
if (Double.IsNaN(0 / zero)) 
{
    Console.WriteLine("Double.IsNan() can determine whether a value is not-a-number.");
}

You should also be aware that none of the comparisons you've shown are actually occurring "as is". When you write floatValue == doubleValue, the floats will actually be implicitly converted to doubles before the comparison occurs.


Probably because NaN != NaN


To quote wikipedia:

A comparison with a NaN always returns an unordered result even when comparing with itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜