将Double.NaN与其自身进行比较 [英] Comparing Double.NaN with itself

查看:146
本文介绍了将Double.NaN与其自身进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出为什么这两个操作返回不同的值:


  1. Double.NaN = = Double.NaN 返回 false

  2. Double.NaN.Equals(Double .NaN)返回 true

我有第一部分的回答而不是第二部分为什么这两个比较返回不同的值

解决方案

差异的原因很简单,如果不明显。 p>

如果您使用等式运算符 == ,那么您正在使用IEEE测试进行相等性。



如果您使用的是 Equals(object)方法,则必须保留的Object.Equals(对象)。当您实现此方法(和相应的 GetHashCode 方法)时,您必须维护该合同,这与IEEE的行为不同。



如果等于合同没有得到维护,那么哈希表的行为就会破裂。

  var map = new Dictionary< double,string>(); 
map [double.NaN] =NaN;
var s = map [double.NaN];

如果!double.NaN.Equals(double.NaN),你永远不会从字典中获得你的价值!



如果上一句没有意义,那么明白哈希的机制在字典< T,U> HashSet< T> 等)同时使用 object.Equals(object) object.GetHashCode()方法广泛,并依赖于他们行为的保证。


I am stuck trying to find out why these two operations return different values:

  1. Double.NaN == Double.NaN returns false
  2. Double.NaN.Equals(Double.NaN) returns true

I have the answer to the first part but not the second and not to "why are these two comparisons returning different values"

解决方案

The reason for the difference is simple, if not obvious.

If you use the equality operator ==, then you're using the IEEE test for equality.

If you're using the Equals(object) method, then you have to maintain the contract of object.Equals(object). When you implement this method (and the corresponding GetHashCode method), you have to maintain that contract, which is different from the IEEE behaviour.

If the Equals contract was not upheld, then the behaviour of hash tables would break.

var map = new Dictionary<double,string>();
map[double.NaN] = "NaN";
var s = map[double.NaN];

If !double.NaN.Equals(double.NaN), you'd never get your value out of the dictionary!

If the previous sentence does not make sense, then understand that the mechanics of hashing (used in Dictionary<T,U>, HashSet<T>, etc) use both the object.Equals(object) and object.GetHashCode() methods extensively, and rely upon guarantees of their behaviour.

这篇关于将Double.NaN与其自身进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆