Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 290
Justin Avatar asked Apr 01 '13 02:04

Justin


2 Answers

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.

like image 130
Sergey Kalinichenko Avatar answered Oct 08 '22 13:10

Sergey Kalinichenko


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.

like image 21
Solomon Slow Avatar answered Oct 08 '22 15:10

Solomon Slow