I have a double[]
and it has a value which is NaN
. When I add up the array's elements, the NaN
makes the result NaN
too.
How did it happen? How can I prevent this NaN
from being added to the rest of my array?
I have a double[]
and it has a value which is NaN
. When I add up the array's elements, the NaN
makes the result NaN
too.
How did it happen? How can I prevent this NaN
from being added to the rest of my array?
NaN
stands for Not-a-Number. It can arise in a variety of ways, for example as a result of 0./0.
, sqrt(-1)
, or as the result of a calculation involving other NaNs
.
The easiest way to check whether v
is a NaN
is by using Double.isNaN(v)
:
public static double sum(double arr[]) {
double sum = 0.0;
for (double val : arr) {
if (!Double.isNaN(val)) {
sum += val;
}
}
return sum;
}
edit: @Stephen C makes a good point in the comments: before deciding to ignore that NaN
, it would be prudent to understand where it came from. It could be that it is the result of a bug elsewhere in your code, and by blindly ignoring the NaN
you could simply be masking the bug instead of fixing it.
NaN stands for "Not a Number", so "Not A Number" + 10 = "Not a Number"
You might want to consider debuggin your app to find what's in the double array :)
how can i prevent that this NaN not bein added to the rest of my double[]
This way:
double[] array = something;
double sum = 0;
for (int i = 0; i < array.length; i++) {
if (!Double.isNaN(array[i])) {
sum += array[i];
}
}
Javadoc for NaN
public static final double NaN
A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.longBitsToDouble(0x7ff8000000000000L).
And relevant section of the JVM spec says any operation involving a NaN
is also a NaN
(a bit like a null
in SQL)
You can't just ignore the NaN, it's an indicator of a problem with you're program. You need to find out what is causing the NaN and fix that.
NaN - Not a Number
btw try :
double[] array = new double[10];
String result = StringUtils.join(array);
System.out.println(result+ " BATMAN !");
Java isn't my strong suit, but in other languages this comes from assigning a value from a string. Try this:
parseDouble
public static double parseDouble(String s)
throws NumberFormatException
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double. Parameters: s - the string to be parsed. Returns: the double value represented by the string argument. Throws: NumberFormatException - if the string does not contain a parsable double. Since: 1.2 See Also: valueOf(String)
Taken from here.