Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is checking a double for equality ever safe?

I have the following code:

double x = 0;  { ...do stuff ...}  if(x == 0){  } 

I was always taught that you shouldn't check floats for equality. Is checking to see if it is equal to zero any different?

like image 789
Steve Avatar asked Aug 24 '11 19:08

Steve


People also ask

Is double compare safe?

In general, no it is not safe due to the fact that so many decimal numbers cannot be precisely represented as float or double values. The often stated solution is test if the difference between the numbers is less than some "small" value (often denoted by a greek 'epsilon' character in the maths literature).

Can you use == to compare doubles?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.

How do you check for doubles equality?

equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same.

What is a double equality?

Double equals are officially known as the abstract equality comparison operator or loose equality. it will compare two elements irrespective of their datatype. It also converts the variable values to the same type before performing a comparison.


1 Answers

The reason you shouldn't check floats for equality is that floating point numbers are not perfectly precise -- there's some inaccuracy in storage with some numbers, such as those that extended too far into the mantissa and repeating decimals (note that I'm talking about repeating decimals in base 2). You can think of this imprecision as "rounding down". The digits that extend beyond the precision of the floating-point number are truncated, effectively rounding down.

If it has not changed, it will keep that equality. However, if you change it even slightly, you probably should not use equalities, but instead a range like (x < 0.0001 && x > -.0001).

In short: as long as you're not playing with x at a very small level, it's OK.

like image 76
Ryan Amos Avatar answered Sep 16 '22 16:09

Ryan Amos