Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to handle NaN in Java?

Tags:

java

double

For example, if you are computing the precision

p = correct / total

Would you make sure you don't divide by zero:

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?

like image 600
schmmd Avatar asked Apr 21 '11 00:04

schmmd


People also ask

What's the best way to handle NaN values?

Because most of the machine learning models that you want to use will provide an error if you pass NaN values into it. The easiest way is to just fill them up with 0, but this can reduce your model accuracy significantly.

Which method in Java is used to check for NaN values?

isNaN() method This method returns true if the value represented by this object is NaN; false otherwise.

Is NaN a logical error in Java?

In Java, "NaN" stands for "not a number" and signifies that a value is not defined. "NaN" is not an exception error, but a value that is assigned. For example, imaginary numbers like the square root of negative numbers or zero divided by zero will both print "NaN" as the result.

Is NaN a double Java?

Java defines NaN constants of both float and double types as Float. NaN and Double. NaN: “A constant holding a Not-a-Number (NaN) value of type double.


1 Answers

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.

like image 77
corsiKa Avatar answered Oct 03 '22 12:10

corsiKa