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?
In Java, when is a float equal to zero?
Asked Answered
You asked question and you answer at the same time –
Vin
@Vin Nothing wrong with that, see stackoverflow.com/help/self-answer. –
Zebapda
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 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
© 2022 - 2024 — McMap. All rights reserved.