Using the Random Module.

Steven D'Aprano steve at
Sat Jul 12 16:06:09 CEST 2008

On Fri, 11 Jul 2008 12:27:32 -0700, castironpi wrote:

> You want a random integer.  Is there a range you want it in?
> Past a certain point, you'll exceed the granularity of the random number
> generator, and some values in the range will never be generated.

You might want to produce an unbounded random integer, where *every* 
integer has a chance to be returned:

def unbounded_randint():
    i = 0
    while True:
        if random.random() < 0.5:
            return i
        i += 1

This returns 0 with probability 1/2, 1 with probability 1/4, 2 with 
probability 1/8, etc. The probability distribution is centered close to 
zero (the mode and median are both zero, and I'm too lazy to calculate 
the mean) and it has an infinitely long tail.


More information about the Python-list mailing list