开发者

How to represent NaN in array of numbers?

开发者 https://www.devze.com 2023-02-08 17:56 出处:网络
The question says it all. I have anarray of doubles and am doing something with them. double expectedOutput[] = { 6.38792, 12.91079, 14.33333, 13.44517,

The 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 test to see if

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

Under certain conditions, i end up with the situation like

6.38792 != NaN

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

I either need to include NaNs into my array of expected elements or somehow figure out that result is Not A Number

I am开发者_JS百科 using Java


In Java, you can get NaN by using

Double.NaN

So you can just put this into your array.

If your question is how to check if something is NaN, you can call

Double.isNan(/* ... value ... */);


You'll have to test for it explicitly, since NaN != NaN, you can't just include it in your array. You have to use Double.isNaN(x).


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

Alternatively:

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


Since in many languages NaN is not equal to itself (and in Java also), you should handle 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.


This is a case where Double objects actually are more useful than primitive doubles.

// 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 in fact implements the reflexivity condition of the equals contract, meaning that Double.valueOf(Double.NaN).equals(Double.valueOf(Double.NaN)) gives true, contrary to Double.NaN != Double.NaN.

0

精彩评论

暂无评论...
验证码 换一张
取 消