user3663882
user3663882

Reputation: 7357

Comparing double for equality is not safe. So what to do if want to compare it to 0?

I know that because of binary double representation, comparison for equality of two doubles is not quite safe. But I need to perform some computation like this:

double a;
//initializing
if(a != 0){       // <----------- HERE
    double b = 2 / a;
   //do other computation
}
throw new RuntimeException();

So, comparison of doubles is not safe, but I definitely do not want to to devide by 0. What to do in this case?

I'd use BigDecimal but its performance is not quite acceptable.

Upvotes: 2

Views: 218

Answers (2)

What about using the Static method compare of the Double class wrapper??

double a = 0.0;
// initializing
if (Double.compare(a, 0.0) != 0) {

}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074238

Well, if your issue is dividing by zero, the good news is that you can do what you have since if the value isn't actually 0, you can divide by it, even if it's really, really small.

You can use a range comparison, comparing it to the lowest value you want to allow, e.g. a >= 0.0000000000001 or similar (if it's always going to be positive).

Upvotes: 5

Related Questions