Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

When Math.signum(x) == 0.

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

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

When it is equal to 0.0 or -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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top