Reputation: 7357
I know that because of binary double representation, comparison for equality of two double
s 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 double
s 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
Reputation: 48258
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
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