Previous Section Next Section

15.3 The random Module

The random module generates pseudo-random numbers with various distributions. The underlying uniform pseudo-random generator uses the Whichmann-Hill algorithm, with a period of length 6,953,607,871,644. The resulting pseudo-random numbers, while quite good, are not of cryptographic quality. If you want physically generated random numbers rather than algorithmically generated pseudo-random numbers, you may use /dev/random or /dev/urandom on platforms that support such pseudo-devices (such as recent Linux releases). For an alternative, see http://www.fourmilab.ch/hotbits.

All functions of module random are methods of a hidden instance of class random.Random. You can instantiate Random explicitly to get multiple generators that do not share state. Explicit instantiation is advisable if you require random numbers in multiple threads (threads are covered in Chapter 14). This section documents the most frequently used functions exposed by module random.

choice

choice(seq)

Returns a random item from non-empty sequence seq.

getstate

getstate(  )

Returns an object S that represents the current state of the generator. You can later pass S to function setstate in order to restore the generator's state.

jumpahead

jumpahead(n)

Advances the generator state as if n random numbers had been generated. Computing the new state is faster than generating n random numbers would be.

random

random(  )

Returns a random floating-point number r from a uniform distribution, such that 0<=r<1.

randrange

randrange([start,]stop[,step])

Like choice(range(start,stop,step)), but faster, since randrange does not need to build the list that range would create.

seed

seed(x=None)

Initializes the generator state. x can be any hashable object. When x is None, and also automatically when module random is first loaded, seed uses the current system time to get a seed. x is normally a long integer up to 27814431486575L. Larger x values are accepted, but may produce the same generator states as smaller ones.

setstate

setstate(S)

Restores the generator state. S must be the result of a previous call to getstate.

shuffle

shuffle(alist)

Shuffles, in place, mutable sequence alist.

uniform

uniform(a,b)

Returns a random floating-point number r from a uniform distribution, such that a<=r<b.

Module random also supplies functions that generate pseudo-random floating-point numbers from many other probability distributions (Beta, Gamma, exponential, Gauss, Pareto, etc.). All of these functions internally call random.random as their source of randomness.

    Previous Section Next Section