在 Java 中,什么时候浮点数等于零?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19397760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:48:34  来源:igfitidea点击:

In Java, when is a float equal to zero?

javazerofloating-point-precision

提问by Wilco

For what values of x does the test (x == 0) return true? Is there some kind of margin or does the test return true if and only if the value of x = 0?

对于 x 的哪些值,测试 (x == 0) 返回 true?是否存在某种边际,或者当且仅当 x = 0 时测试返回 true?

采纳答案by Wilco

A simple method can be written to find this value.

可以编写一个简单的方法来找到这个值。

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

This outputs the following:

这将输出以下内容:

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

This (and similar tests) show that (x == 0) really only is true when x is 0.0f or -0.0f

这个(和类似的测试)表明 (x == 0) 只有当 x 为 0.0f 或 -0.0f 时才为真

回答by OldCurmudgeon

When it is equal to 0.0or -0.0.

当它等于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"));
}

prints

印刷

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

回答by JonAar Livernois

When Math.signum(x)== 0.

Math.signum(x)== 0。

All other attempts to check whether float x== 0 may fail.

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

But Math.signum() is so basic, it should never fail.

但是 Math.signum() 非常基础,它永远不会失败。