Programming

How do I generate random numbers in Python?

steloflute 2012. 5. 29. 17:38
http://effbot.org/pyfaq/how-do-i-generate-random-numbers-in-python.htm

 

How do I generate random numbers in Python?

The standard random module implements a random number generator. Usage is simple:

import random
print random.random()

This prints a random floating point number in the range [0, 1) (that is, between 0 and 1, including 0.0 but always smaller than 1.0).

There are also many other specialized generators in this module, such as:

  • randrange(a, b) chooses an integer in the range [a, b).
  • uniform(a, b) chooses a floating point number in the range [a, b).
  • normalvariate(mean, sdev) samples the normal (Gaussian) distribution.

Some higher-level functions operate on sequences directly, such as:

  • choice(S) chooses a random element from a given sequence (the sequence must have a known length).
  • shuffle(L) shuffles a list in-place, i.e. permutes it randomly

There’s also a Random class you can instantiate to create independent multiple random number generators.

CATEGORY: library