How to represent NaN in an array of numbers?

This question says it all. I have an array of doubles and am doing something with them.

double expectedOutput[] = { 6.38792, 12.91079, 14.33333, 13.44517, 12.34539, 12.05397, 8.34061, 2.07900, -2.01999, -5.47802, -8.21610, -9.26719, -11.02378 }; 

Ideally, I would check if

6.38792 == 6.38792 and you end up with 'pass'

Under certain conditions, I get a situation like

 6.38792 != NaN 

Knowing that this is a random case sometimes, how can I represent NaN in my code?

Do I need to include NaNs in my array of expected elements or somehow figure out that the result is not A Number

I am using java

+4
source share
5 answers

In Java, you can get NaN using

 Double.NaN 

So you can just put this in your array.

If you have a question how to check if there is something NaN, you can call

 Double.isNan(/* ... value ... */); 
+5
source

You will need to check it explicitly, since NaN != NaN , you cannot just include it in your array. You must use Double.isNaN(x) .

+4
source
 double d = 0.0/0.0; if(Double.isNan(d)){ // Double d is not a number. } 

As an alternative:

 double d = Double.Nan; if(Double.isNan(d)){ // Double d is not a number. } 
+1
source

Since NaN is not equal to itself in many languages ​​(and in Java, too), you should treat it as a specific case. Use Float.NaN or Double.NaN to reference NaN. Use Float.isNaN or Double.isNaN to check if a specific value is NaN.

0
source

This is the case when Double objects are actually more useful than primitive Double s.

 // auto-boxes them all to Double objects Collection<Double> expectedOutput = Arrays.asList(6.38792, 12.91079, 14.33333, 13.44517, 12.34539, 12.05397, 8.34061, 2.07900, -2.01999, -5.47802, -8.21610, -9.26719, -11.02378, Double.NaN ); // maybe fill into HashSet for more efficient lookup? // later: double d = Double.NaN; if(expectedOutput.contains(d)) { System.out.println("found"); } 

The reason is that Double.equals actually implements the reflexivity condition of an equal contract, which means that Double.valueOf(Double.NaN).equals(Double.valueOf(Double.NaN)) gives true , contrary to Double.NaN != Double.NaN .

0
source

Source: https://habr.com/ru/post/1338667/


All Articles