Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way to compare a System.Double to '0' (a number, int?)

Tags:

c#

compare

Sorry, this might be a easy stupid question, but I need to know to be sure.

I have this if expression,

void Foo() {     System.Double something = GetSomething();     if (something == 0) //Comparison of floating point numbers with equality                       // operator. Possible loss of precision while rounding value         {} } 

Is that expression equal with

void Foo() {     System.Double something = GetSomething();     if (something < 1)         {} } 

? Because then I might have a problem, entering the if with e.g. a value of 0.9.

like image 869
radbyx Avatar asked Jul 06 '11 14:07

radbyx


People also ask

How do you compare double numbers?

To compare two floating point or double values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

Can we compare double and int in C#?

If you have not done any calculations using the double, you can just use == . This is because an integer can be represented by a double exactly (only between -2^53 and 2^53). int iValue = 0; double dValue = 0.0; bool isEqual = iValue == dValue; This returns true.


2 Answers

Well, how close do you need the value to be to 0? If you go through a lot of floating point operations which in "infinite precision" might result in 0, you could end up with a result "very close" to 0.

Typically in this situation you want to provide some sort of epsilon, and check that the result is just within that epsilon:

if (Math.Abs(something) < 0.001) 

The epsilon you should use is application-specific - it depends on what you're doing.

Of course, if the result should be exactly zero, then a simple equality check is fine.

like image 81
Jon Skeet Avatar answered Sep 28 '22 09:09

Jon Skeet


If something has been assigned from the result of an operation other than something = 0 then you better use:

if(Math.Abs(something) < Double.Epsilon) { //do something } 

Edit: This code is wrong. Epsilon is the smallest number, but not quite zero. When you wish to compare a number to another number, you need to think of what is the acceptable tolerance. Let's say that anything beyond .00001 you don't care about. That's the number you'd use. The value depends on the domain. However, it's mostly certainly never Double.Epsilon.

like image 40
sonatique Avatar answered Sep 28 '22 11:09

sonatique