What is the right way to handle NaN in Java?
For example, if you are computing the precision
p = correct / total
Would you make sure you don't divide by ze开发者_如何学运维ro:
double p;
if (total == 0.0) {
p = 0.0;
}
else {
p == correct / total;
}
Or check if you get a NaN?
double p = correct / total;
if (Double.isNaN(p)) {
p = 0.0;
}
Is there a benefit to an approach, or is it personal preference?
I would use the first approach, but instead of comparing to 0, I would compare the Math.abs(total) < TOLERANCE
where TOLERANCE is some small value like 0.0001. This will prevent things very close to 0 from skewing results.
精彩评论