Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Assert Double is NaN [closed]

I am trying to assert that my double is NaN. Here is a code snippet:

private Double calculateIt(String input){...}

assertEquals(Double.NaN, calculateIt("input text"));

The code does not compile, Double.NaN is defined as primitive

public static final double NaN = 0.0d / 0.0;

To make the assertion work I wrap NaN with a Double object.

assertEquals(new Double(Double.NaN), calculateIt("input text"));

Is there a shorter way to do this?

like image 546
Oleh Novikov Avatar asked Feb 22 '16 12:02

Oleh Novikov


People also ask

How do you know if a double equals NaN?

Java Double isNaN() Method The isNaN() method of Java Double class returns true: If the value of this Object is Not-a-Number (NaN). If the argument passed is Not-a-Number (NaN). Otherwise, the method returns false.

Can double Be NaN 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.

How does Java handle NaN?

In mathematics, taking the square root of a negative number results in an imaginary number. This case is dealt with by returning NaN in Java. Taking mod of a number with zero, will return the remainder after dividing a value by zero. Hence, NaN is returned.

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.


1 Answers

You could use:

boolean isNan = Double.isNaN(calculateIt("input text"));
assertTrue(isNan);

Double.NaN values cannot be compared with == (Double.NaN == Double.NaN will return false), because NaN is considered as a special one.

More info:

  • IEEE floating point
like image 150
Konstantin Yovkov Avatar answered Oct 18 '22 05:10

Konstantin Yovkov