Range of python's random.random() from the standard library

>>> 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

Tags:

Python

Random