random number including 1 - i.e. [0,1]

dickinsm at gmail.com dickinsm at gmail.com
Wed Jun 10 09:13:53 EDT 2009


Esmail <ebonak at hotmail.com> wrote:
> Hi,
> 
> random.random() will generate a random value in the range [0, 1).
> 
> Is there an easy way to generate random values in the range [0, 1]?
> I.e., including 1?
> 
> [...]

Here are three recipes, each more pedantic than the last.  They all
assume that Python floats are IEEE 754 binary64 format (which they
almost certainly are on your machine), and that randrange generates
all values with equal likelihood (which it almost certainly doesn't,
but the assumption should be good enough for government work).


import random

def random1():
    """Random float in [0, 1].  Generates all floats of the form n/2**53,
    0 <= n <= 2**53, with equal probability.

    """
    return random.randrange(2**53+1)/2.**53

def random2():
    """Random float in [0, 1].  Generates all floats of the forn n/2**53,
    0 <= n <= 2**53, with values in (0.0, 1.0) equally likely, and the
    endpoints 0.0 and 1.0 occuring with half the probability of any
    other value.

    This is equivalent to generating a random real number uniformly on
    the closed interval [0, 1] and then rounding that real number to the
    nearest float of the form n/2**53.

    """
    return (random.randrange(2**54)+1)//2/2.**53

def random3():
    """Random float in [0, 1].  Generates *all* floats in the interval
    [0.0, 1.0] (including 0.0 and 1.0, but excluding -0.0).  Each
    float is generated with a probability corresponding to the size of
    the subinterval of [0, 1] that rounds to the given float under
    round-to-nearest.

    This is equivalent to generating a random real number uniformly on
    the closed interval [0, 1] and then rounding that real number to
    the nearest representable floating-point number.

    """
    m = (random.randrange(2**53)+1)//2
    e = 1022
    while random.randrange(2) and e:
        e -= 1
    return (m+2**52) * 2.**(e-1075) if e else m*2.**-1074



-- 
Mark Dickinson



More information about the Python-list mailing list