双重比较零特殊情况? [英] double comparison to zero special case?

查看:59
本文介绍了双重比较零特殊情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在初始化一个双精度数组:

I'm initializing a double array:

double [] foo = new double[n];

我的理解是Java语言规范导致数组中的所有值都初始化为零。

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)

或我应该在那里使用epsilon吗?或者类似地,如果我想知道是否未设置值,是否可以使用 == ,因为零将不会被计算出来,而是原始的初始化零?当然,通常我通常不会使用 == 来比较浮点数,但是我想知道这是否是特例吗?

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?

谢谢!

推荐答案

考虑此代码

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);
        }
    }
}

输出

 foo[5] = 10.000000

这篇关于双重比较零特殊情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆