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?
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With