开发者

Equals() for double values in .NET. Wrong implementation or not?

开发者 https://www.devze.com 2023-02-09 11:47 出处:网络
Merged with c# NaN comparison differences between Equals() and ==. I always thought that \"==\" and Equals() give same result for double values...But this is not true
Merged with c# NaN comparison differences between Equals() and ==.

I always thought that "==" and Equals() give same result for double values...But this is not true

Example

    var a = Double.NaN;

    Console.WriteLine(a == a);
    Console.ReadKey();

Prints "False"

    var a = Double.NaN;

    Console.WriteLine(a.Equals(a));
    Console.ReadKey();

Prints "True"!

So, why Equals() met开发者_如何学JAVAhod implementation for floating point numbers does not follow floating point numbers specification, which says that if number is NaN - it is not equal to anything, even to itself?

P.S I merged my questions and will delete another about NaN's as soon as possible

P.P.S Equals realization (.NET 4, thanks to Ani)

public bool Equals(double obj)
{
    return ((obj == this) || (IsNaN(obj) && IsNaN(this)));
}
0

精彩评论

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

关注公众号