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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The smallest positive value of a double is
Double.MIN_NORMAL
. So, the largest number less than 1.0 is1.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 of1.0-Double.MIN_NORMAL
to 308 decimal places before you could see anything but a 9.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 thana
(i.e., the next value aftera
), andMath.nextAfter(a, -1.0)
returns the greatest value that is less thana
(i.e., the value beforea
).Note: Another poster said,
1.0-Double.MIN_NORMAL
. That's wrong.1.0-Double.MIN_NORMAL
is exactly equal to 1.0.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 roughly0.9999999999999998
.References: IEEE-754 Calculator.