问题
I'm initializing a double array:
double [] foo = new double[n];
My understanding is that the java language specification causes all the values in the array to be initialized to zero.
As I go through my algorithm, some of the entries in the array get set to a positive value.
So to check whether a particular element has a non-zero value set, is it safe to just use
if (foo[i] > 0.0)
or should I be using an epsilon there. Or similarly if I want to know if a value has not been set, could I use ==
given that the zeros will not have been computed values, but the original initialized zeros? Normally of course I would never use ==
to compare floating point numbers, but I wonder if this is a special case?
Thanks!
回答1:
Consider this code
public static void main(String[] args) {
double [] foo = new double[10];
foo[5] = 10; // Sets the sixth element to 10
for (int i = 0; i < foo.length; i++) {
double val = foo[i];
if (val != 0) {
System.out.printf("foo[%d] = %f\n", i, val);
}
}
}
It outputs
foo[5] = 10.000000
回答2:
There shouldn't be a problem with using
if (foo[i] > 0.0)
来源:https://stackoverflow.com/questions/21005444/double-comparison-to-zero-special-case