Compare Double.MIN_VALUE and 0
Why doesn't this code work? In fact, this is just a small part of a larger program. It has to compare Double.MIN_VALUE
with different values, it works with all values except 0.
why? Thank you!
double d = Double.MIN_VALUE;
if (0. > d) {
System.out.println("OK");
}
Double.MIN_VALUE
- 4.9E-324
. And that's not less 0
. But it really isn't 0
.
If you print
System.out.println(4.9E-324d > 0.);//this is true
In this sense
0.0000000000 ... 0001! = 0. But it tends to 0
Similar 4.9E-324d != 0 but tends to 0
You are comparing decimal numbers. If you say try something like:
System.out.println(0.000000000000001d == 0.);//print false
You will receive a lie. If I read the java docs it says:
/**
* A constant holding the smallest positive nonzero value of type
* {@code double}, 2<sup>-1074</sup>. It is equal to the
* hexadecimal floating-point literal
* {@code 0x0.0000000000001P-1022} and also equal to
* {@code Double.longBitsToDouble(0x1L)}.
*/
So it is close to zero, but not really 0.
Double.MIN_VALUE
is actually a bad name for a constant in Java. It is not suitable for int.MIN_VALUE
. In C # it is called Double.Epsilon which IMHO suits better.
So, Double.MIN_VALUE
not the biggest negative double that exists. IMHO such a constant doesn't even exist in JAVA by default.
Double.MIN_VALUE
is equal to a hexadecimal floating point literal 0x0.0000000000001P-1022
and also equalDouble.longBitsToDouble(0x1L).
So, your condition is not triggered!
If you want to compare the value with the smallest number (the negative value with the largest value), you can look Double.NEGATIVE_INFINITY
at which is stated in the Java documentation:
"A constant that stores negative infinity of type double. It is equal to the value returned by Double.longBitsToDouble (0xfff0000000000000L).