Does python's random.random() ever return 1.0 or does it only return up until 0.9999..?
Almost all module functions depend on the basic function random() , which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator.
random() function generates random floating numbers in the range[0.1, 1.0).
The random() function generates a floating number in the half-open interval — [0,1). This means that the number generated will be from 0 to 1 (where 1 is excluded). The sample() function is useful for cases such as lucky draws where you need to pick some winners from a list of values.
Python Random random() Method The random() method returns a random floating number between 0 and 1.
>>> help(random.random)
Help on built-in function random:
random(...)
random() -> x in the interval [0, 1).
That means 1 is excluded.
Docs are here: http://docs.python.org/library/random.html
...random(), which generates a random float uniformly in the semi-open range [0.0, 1.0).
So, the return value will be greater than or equal to 0, and less than 1.0.
The other answers already clarified that 1 is not included in the range, but out of curiosity, I decided to look at the source to see precisely how it is calculated.
The CPython source can be found here
/* random_random is the function named genrand_res53 in the original code;
* generates a random number on [0,1) with 53-bit resolution; note that
* 9007199254740992 == 2**53; I assume they're spelling "/2**53" as
* multiply-by-reciprocal in the (likely vain) hope that the compiler will
* optimize the division away at compile-time. 67108864 is 2**26. In
* effect, a contains 27 random bits shifted left 26, and b fills in the
* lower 26 bits of the 53-bit numerator.
* The orginal code credited Isaku Wada for this algorithm, 2002/01/09.
*/
static PyObject *
random_random(RandomObject *self)
{
unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
So the function effectively generates m/2^53
where 0 <= m < 2^53
is an integer. Since floats have 53 bits of precision normally, this means that on the range [1/2, 1), every possible float is generated. For values closer to 0, it skips some possible float values for efficiency but the generated numbers are uniformly distributed within the range. The largest possible number generated by random.random
is precisely
0.99999999999999988897769753748434595763683319091796875
Python's random.random
function returns numbers that are less than, but not equal to, 1
.
However, it can return 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With