Why does Resharper complain when I compare a double to zero?

ε祈祈猫儿з 提交于 2019-12-12 10:29:10

问题


If I do

double d = 0;
if (d == 0) {
  ...
}

Resharper complains at the comparison d == 0 about "Comparison of floating point number with equality operator. Possible loss of precision while rounding values."

Why? It cannot be difficult to represent exact zero as a double or a float can it?

I understand such a warning would be relevant if I compared to some other value such as 0.2 for which there is no exact binary representation.


回答1:


Resharper does not analyze how the double variable got its value.

After a few calculations a double value is rarely exact so resharper warns you that comparing a double with an exact value is not a good idea.

double x = Math.Sqrt(2);
double d = x * x;

Console.WriteLine(d == 2);



回答2:


Since R# 6, many such inspections have a 'Why is ReSharper suggesting this?' item on their Alt+Enter menu. In this case, the explanation relates to the possible unintended consequences of doing equality comparisons on floating point values:

Using the == operator to compare floating-point numbers is, generally, a bad idea. The problem arises from the fact that, typically, results of calculations have to be ‘fitted’ into floating-point representation, which does not always matched the perceived reality of what result should be produced.




回答3:


often calculation with double is inexact. comparing a double with an exact value may be problematic. Comparing with an intervallmight be more secure.

if ((d > -0.000001) && (d < +0.000001)) {
   ...
}

the same appy when comparing dates

if ((date >= DateTime.parse("2012-05-21T00:00:00")) && 
   (date <= DateTime.parse("2012-05-21T23:59:59"))) {
}


来源:https://stackoverflow.com/questions/10684365/why-does-resharper-complain-when-i-compare-a-double-to-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!