Java: Math.random() Max Value (double just less th

2019-06-19 01:15发布

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?

3条回答
你好瞎i
2楼-- · 2019-06-19 01:31

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.

查看更多
Fickle 薄情
3楼-- · 2019-06-19 01:32

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.

查看更多
祖国的老花朵
4楼-- · 2019-06-19 01:35

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.

查看更多
登录 后发表回答