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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With