In Java, when is a float equal to zero?
Asked Answered
W

3

8

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?

Westernize answered 16/10, 2013 at 7:42 Comment(2)
You asked question and you answer at the same timeVin
@Vin Nothing wrong with that, see stackoverflow.com/help/self-answer.Zebapda
W
9

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

Westernize answered 16/10, 2013 at 7:42 Comment(0)
G
11

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.

Gunner answered 11/4, 2015 at 21:10 Comment(0)
W
9

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

Westernize answered 16/10, 2013 at 7:42 Comment(0)
L
3

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
Lesson answered 16/10, 2013 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.