I've been a little curious about this. Math.random() gives a value in the range [0.0,1.0). So what might the largest value it can give be? In other words, what is the closest double value to 1.0 that is less than 1.0?
问题:
回答1:
Java uses 64-bit IEEE-754 representation, so the closest number smaller than one is theoretically 3FEFFFFFFFFFFFFF
in hexadecimal representation, which is 0 for sign, -1 for the exponent, and 1.9999999999999997 for the 52-bit significand. This equals to roughly 0.9999999999999998
.
References: IEEE-754 Calculator.
回答2:
The number that you want is returned by Math.nextAfter(1.0, -1.0)
.
The name of the function is somewhat of a misnomer. Math.nextAfter(a, 1.0)
returns the least double value that is greater than a
(i.e., the next value after a
), and Math.nextAfter(a, -1.0)
returns the greatest value that is less than a
(i.e., the value before a
).
Note: Another poster said, 1.0-Double.MIN_NORMAL
. That's wrong. 1.0-Double.MIN_NORMAL
is exactly equal to 1.0.
回答3:
The smallest positive value of a double is Double.MIN_NORMAL
. So, the largest number less than 1.0 is 1.0-Double.MIN_NORMAL
.
Double.MIN_NORMAL
is equal to 2-1022, so the answer is still extremely close to 1.0. You'd have to print the value of 1.0-Double.MIN_NORMAL
to 308 decimal places before you could see anything but a 9.