开发者

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

开发者 https://www.devze.com 2023-02-15 06:03 出处:网络
Why float.NaN != double.NaN ? while float.PositiveInfinity == double.PositiveInfinity and float.NegativeInfinity == double.NegativeInfinity are equal.

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

精彩评论

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