Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to compare a double to 0 like this: doubleVariable==0?

Tags:

c#

double

It is ok to do this?

double doubleVariable=0.0;
if (doubleVariable==0) {
   ...
}

Or this code would suffer from potential rounding problems?

like image 542
Nestor Avatar asked Apr 14 '11 05:04

Nestor


2 Answers

Nope it's perfectly legal if you are only going to compare against 0 as the right side of comparison will automatically casted to double. On the other hand, it would yield all the round-off errors if you where to compare against == 0.10000001

You are better or reading the discussion about float to 0 comparison here: Is it safe to check floating point values for equality to 0?

Also this discussion is very informative about weird precision problems on floats: Why the result is different for this problem?

i.e. below will yield false:

double d1 = 1.000001; double d2 =0.000001;
Console.WriteLine((d1-d2)==1.0);
like image 105
Teoman Soygul Avatar answered Oct 11 '22 23:10

Teoman Soygul


What you have there is 0, which is an integer literal. It is implicitly converted to a double which you could represent with the double literal 0.0 (implicit conversion). Then there is a comparison between the two doubles. A rounding error could cause doubleVariable to not be equal to 0.0 (by some other math you might do, not just setting it), but there could never be a rounding error when converting the integer 0 to double. The code you have there is totally safe, but I would favor == 0.0 instead.

like image 29
Eric Mickelsen Avatar answered Oct 11 '22 22:10

Eric Mickelsen