问题
Below I attempt to assign to value
the maximum Long
value, then add to it the minimum positive Double
value possible.
I then try to detect that the value is greater than the maximum Long
value.
Double value = new Long(Long.MAX_VALUE).doubleValue();
value += Double.MIN_VALUE;
if (value < -(new Long(Long.MAX_VALUE).doubleValue()) || value > new Long(Long.MAX_VALUE).doubleValue()) {
// Expecting code here to execute, but it doesn't.
}
Studying the values involved shows that value
has the final value of
9.223372036854776E18
= 9223372036854776000
while Long.MAX_VALUE
has the value
9223372036854775807
Comparing these shows that value
is greater as expected:
9223372036854776000 (value)
9223372036854775807 (Long.MAX_VALUE)
Could someone please explain why the if
statement fails to detect this?
Sincere thanks.
回答1:
Long.MAX_VALUE
can't be represented exactly as a double. The closest available double value is 9223372036854775808
.
Adding Double.MIN_VALUE
to that number (10^-1074) does not change anything because the closest double value to 9223372036854775808 + 10^-1074
still is 9223372036854775808
.
Using @PeterLawrey's code, you can see that the next available double is 9223372036854777856
(which is equal to Long.MAX_VALUE + 2048
).
Note: your double is actually equal to 9223372036854775808
, which gets printed as 9.223372036854776E18
. You can see it with the following code:
double d = Long.MAX_VALUE;
BigDecimal bd= new BigDecimal(d);
System.out.println(bd);
回答2:
Adding a very small value to a large value is the same as adding nothing.
I suspect what you had in mind is
double d = Long.MAX_VALUE;
// get the next represented value.
double d1 = Double.longBitsToDouble(Double.doubleToLongBits(d)+1);
System.out.println(d > Long.MAX_VALUE);
System.out.println(d1 > Long.MAX_VALUE);
prints
false
true
来源:https://stackoverflow.com/questions/12355839/java-6-creating-and-detecting-the-first-double-value-above-long-max-value