double comparison to zero special case?

被刻印的时光 ゝ 提交于 2019-12-24 04:18:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!