在Java中,何时浮点值等于零?

时间:2013-10-16 07:42:47

标签: java zero floating-point-precision

对于x的值,测试(x == 0)是否返回真?是否有某种保证金,或者当且仅当x = 0的值时,测试才返回true?

3 个答案:

答案 0 :(得分:7)

可以编写一个简单的方法来查找此值。

public class FloatEqualsZero {
    public static void main(String [] args) {
        float x = 1;
        while(x != 0 && -x != 0) {
            x *= 0.1;
            System.out.println(x);
        }
    }
}

这输出以下内容:

0.1
0.01
9.999999E-4
9.999999E-5
9.999999E-6
9.999999E-7
...
1.0E-37
1.0E-38
1.0E-39
1.0E-40
1.0E-41
1.0E-42
1.0E-43
9.8E-45
1.4E-45
0.0

这(和类似的测试)表明,当x为0.0f或-0.0f

时,(x == 0)真的只有真

答案 1 :(得分:5)

Math.signum(x) == 0。

所有其他尝试检查float x == 0是否可能失败。

但Math.signum()是如此基本,它永远不会失败。

答案 2 :(得分:1)

等于0.0-0.0

public void test() {
  double x = 0.0;
  double y = -0.0;
  double z = 0.0;
  test(x, y);
  test(y, z);
  test(x, z);
  test(x, (int)y);
  test(y, (int)z);
  test(x, (int)z);

}

private void test(double x, double y) {
  System.out.println("x=" + x + " y=" + y + " \"x == y\" is " + (x == y ? "true" : "false"));
}

private void test(double x, int y) {
  System.out.println("x=" + x + " y=" + y + " \"x == y\" is " + (x == y ? "true" : "false"));
}

打印

x=0.0 y=-0.0 "x == y" is true
x=-0.0 y=0.0 "x == y" is true
x=0.0 y=0.0 "x == y" is true
x=0.0 y=0 "x == y" is true
x=-0.0 y=0 "x == y" is true
x=0.0 y=0 "x == y" is true