Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, when is a float equal to zero?

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?

like image 208
Wilco Avatar asked Oct 16 '13 07:10

Wilco


3 Answers

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.

like image 162
JonAar Livernois Avatar answered Oct 20 '22 18:10

JonAar Livernois


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

like image 33
Wilco Avatar answered Oct 20 '22 19:10

Wilco


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
like image 3
OldCurmudgeon Avatar answered Oct 20 '22 19:10

OldCurmudgeon