blob: 2b686ec4ffb5ed0cdea159667708077404b46033 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{random} ---
Fred Drake048b75b1999-04-21 18:14:22 +00002 Generate pseudo-random numbers}
Fred Drakeb91e9341998-07-23 17:59:49 +00003
Fred Drake048b75b1999-04-21 18:14:22 +00004\declaremodule{standard}{random}
Fred Drake295da241998-08-10 19:42:37 +00005\modulesynopsis{Generate pseudo-random numbers with various common
Fred Drake048b75b1999-04-21 18:14:22 +00006 distributions.}
Fred Drakeb91e9341998-07-23 17:59:49 +00007
Guido van Rossum571391b1997-04-03 22:41:49 +00008
9This module implements pseudo-random number generators for various
Tim Peters902446a2001-01-24 23:06:53 +000010distributions.
Raymond Hettinger40f62172002-12-29 23:03:38 +000011
Tim Peters902446a2001-01-24 23:06:53 +000012For integers, uniform selection from a range.
Raymond Hettinger40f62172002-12-29 23:03:38 +000013For sequences, uniform selection of a random element, a function to
14generate a random permutation of a list in-place, and a function for
15random sampling without replacement.
16
Tim Peters902446a2001-01-24 23:06:53 +000017On the real line, there are functions to compute uniform, normal (Gaussian),
18lognormal, negative exponential, gamma, and beta distributions.
Raymond Hettinger40f62172002-12-29 23:03:38 +000019For generating distributions of angles, the von Mises distribution
20is available.
Guido van Rossum571391b1997-04-03 22:41:49 +000021
Tim Peters902446a2001-01-24 23:06:53 +000022Almost all module functions depend on the basic function
23\function{random()}, which generates a random float uniformly in
Raymond Hettinger40f62172002-12-29 23:03:38 +000024the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as
25the core generator. It produces 53-bit precision floats and has a
26period of 2**19937-1. The underlying implementation in C
27is both fast and threadsafe. The Mersenne Twister is one of the most
28extensively tested random number generators in existence. However, being
29completely deterministic, it is not suitable for all purposes, and is
30completely unsuitable for cryptographic purposes.
Tim Peters902446a2001-01-24 23:06:53 +000031
Tim Petersd7b5e882001-01-25 03:36:26 +000032The functions supplied by this module are actually bound methods of a
Fred Drake844bd5b2001-02-02 02:42:31 +000033hidden instance of the \class{random.Random} class. You can
34instantiate your own instances of \class{Random} to get generators
35that don't share state. This is especially useful for multi-threaded
36programs, creating a different instance of \class{Random} for each
37thread, and using the \method{jumpahead()} method to ensure that the
Raymond Hettinger40f62172002-12-29 23:03:38 +000038generated sequences seen by each thread don't overlap.
Fred Drake844bd5b2001-02-02 02:42:31 +000039
40Class \class{Random} can also be subclassed if you want to use a
41different basic generator of your own devising: in that case, override
42the \method{random()}, \method{seed()}, \method{getstate()},
Tim Petersd52269b2001-01-25 06:23:18 +000043\method{setstate()} and \method{jumpahead()} methods.
Raymond Hettinger2f726e92003-10-05 09:09:15 +000044Optionally, a new generator can supply a \method{getrandombits()}
45method --- this allows \method{randrange()} to produce selections
46over an arbitrarily large range.
47\versionadded[the \method{getrandombits()} method]{2.4}
Tim Petersd7b5e882001-01-25 03:36:26 +000048
Raymond Hettinger40f62172002-12-29 23:03:38 +000049As an example of subclassing, the \module{random} module provides
50the \class{WichmannHill} class which implements an alternative generator
51in pure Python. The class provides a backward compatible way to
52reproduce results from earlier versions of Python which used the
53Wichmann-Hill algorithm as the core generator.
54\versionchanged[Substituted MersenneTwister for Wichmann-Hill]{2.3}
Tim Peterse360d952001-01-26 10:00:39 +000055
Tim Petersd7b5e882001-01-25 03:36:26 +000056
57Bookkeeping functions:
Tim Peters902446a2001-01-24 23:06:53 +000058
59\begin{funcdesc}{seed}{\optional{x}}
60 Initialize the basic random number generator.
Tim Peters0de88fc2001-02-01 04:59:18 +000061 Optional argument \var{x} can be any hashable object.
Fred Drake4cacec52001-04-21 05:56:06 +000062 If \var{x} is omitted or \code{None}, current system time is used;
Tim Peters0de88fc2001-02-01 04:59:18 +000063 current system time is also used to initialize the generator when the
64 module is first imported.
Fred Drake4cacec52001-04-21 05:56:06 +000065 If \var{x} is not \code{None} or an int or long,
Fred Draked0946da2001-02-01 15:53:24 +000066 \code{hash(\var{x})} is used instead.
Tim Peters0de88fc2001-02-01 04:59:18 +000067 If \var{x} is an int or long, \var{x} is used directly.
Barry Warsaw83125772001-01-25 00:39:16 +000068\end{funcdesc}
Guido van Rossum571391b1997-04-03 22:41:49 +000069
Tim Petersd7b5e882001-01-25 03:36:26 +000070\begin{funcdesc}{getstate}{}
Fred Drake844bd5b2001-02-02 02:42:31 +000071 Return an object capturing the current internal state of the
72 generator. This object can be passed to \function{setstate()} to
73 restore the state.
Tim Peters0de88fc2001-02-01 04:59:18 +000074 \versionadded{2.1}
75\end{funcdesc}
Fred Drake5f0decf2001-01-22 18:18:30 +000076
Tim Petersd7b5e882001-01-25 03:36:26 +000077\begin{funcdesc}{setstate}{state}
78 \var{state} should have been obtained from a previous call to
Fred Drake844bd5b2001-02-02 02:42:31 +000079 \function{getstate()}, and \function{setstate()} restores the
80 internal state of the generator to what it was at the time
81 \function{setstate()} was called.
Tim Peters0de88fc2001-02-01 04:59:18 +000082 \versionadded{2.1}
Fred Drake844bd5b2001-02-02 02:42:31 +000083\end{funcdesc}
Tim Petersd7b5e882001-01-25 03:36:26 +000084
Tim Petersd52269b2001-01-25 06:23:18 +000085\begin{funcdesc}{jumpahead}{n}
Raymond Hettinger40f62172002-12-29 23:03:38 +000086 Change the internal state to one different from and likely far away from
87 the current state. \var{n} is a non-negative integer which is used to
88 scramble the current state vector. This is most useful in multi-threaded
Fred Drake4cacec52001-04-21 05:56:06 +000089 programs, in conjuction with multiple instances of the \class{Random}
Raymond Hettinger40f62172002-12-29 23:03:38 +000090 class: \method{setstate()} or \method{seed()} can be used to force all
91 instances into the same internal state, and then \method{jumpahead()}
92 can be used to force the instances' states far apart.
Tim Peters0de88fc2001-02-01 04:59:18 +000093 \versionadded{2.1}
Raymond Hettinger40f62172002-12-29 23:03:38 +000094 \versionchanged[Instead of jumping to a specific state, \var{n} steps
95 ahead, \method{jumpahead(\var{n})} jumps to another state likely to be
96 separated by many steps.]{2.3}
Tim Petersd52269b2001-01-25 06:23:18 +000097 \end{funcdesc}
Tim Petersd7b5e882001-01-25 03:36:26 +000098
Raymond Hettinger2f726e92003-10-05 09:09:15 +000099\begin{funcdesc}{getrandbits}{k}
100 Returns a python \class{long} int with \var{k} random bits.
101 This method is supplied with the MersenneTwister generator and some
102 other generators may also provide it as an optional part of the API.
103 When available, \method{getrandbits()} enables \method{randrange()}
104 to handle arbitrarily large ranges.
105 \versionadded{2.4}
106\end{funcdesc}
Raymond Hettinger40f62172002-12-29 23:03:38 +0000107
Tim Petersd7b5e882001-01-25 03:36:26 +0000108Functions for integers:
Fred Drake5f0decf2001-01-22 18:18:30 +0000109
Fred Drake5f0decf2001-01-22 18:18:30 +0000110\begin{funcdesc}{randrange}{\optional{start,} stop\optional{, step}}
111 Return a randomly selected element from \code{range(\var{start},
112 \var{stop}, \var{step})}. This is equivalent to
Tim Peters902446a2001-01-24 23:06:53 +0000113 \code{choice(range(\var{start}, \var{stop}, \var{step}))},
114 but doesn't actually build a range object.
Fred Drake5f0decf2001-01-22 18:18:30 +0000115 \versionadded{1.5.2}
116\end{funcdesc}
117
Tim Petersd7b5e882001-01-25 03:36:26 +0000118\begin{funcdesc}{randint}{a, b}
Tim Petersd7b5e882001-01-25 03:36:26 +0000119 Return a random integer \var{N} such that
120 \code{\var{a} <= \var{N} <= \var{b}}.
121\end{funcdesc}
122
123
124Functions for sequences:
125
126\begin{funcdesc}{choice}{seq}
127 Return a random element from the non-empty sequence \var{seq}.
128\end{funcdesc}
129
130\begin{funcdesc}{shuffle}{x\optional{, random}}
131 Shuffle the sequence \var{x} in place.
132 The optional argument \var{random} is a 0-argument function
133 returning a random float in [0.0, 1.0); by default, this is the
134 function \function{random()}.
135
136 Note that for even rather small \code{len(\var{x})}, the total
137 number of permutations of \var{x} is larger than the period of most
138 random number generators; this implies that most permutations of a
139 long sequence can never be generated.
140\end{funcdesc}
141
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000142\begin{funcdesc}{sample}{population, k}
143 Return a \var{k} length list of unique elements chosen from the
144 population sequence. Used for random sampling without replacement.
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000145 \versionadded{2.3}
Raymond Hettinger311f4192002-11-18 09:01:24 +0000146
147 Returns a new list containing elements from the population while
148 leaving the original population unchanged. The resulting list is
149 in selection order so that all sub-slices will also be valid random
150 samples. This allows raffle winners (the sample) to be partitioned
151 into grand prize and second place winners (the subslices).
152
153 Members of the population need not be hashable or unique. If the
154 population contains repeats, then each occurrence is a possible
155 selection in the sample.
156
157 To choose a sample from a range of integers, use \function{xrange}
158 as an argument. This is especially fast and space efficient for
159 sampling from a large population: \code{sample(xrange(10000000), 60)}.
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000160\end{funcdesc}
161
Tim Petersd7b5e882001-01-25 03:36:26 +0000162
163The following functions generate specific real-valued distributions.
164Function parameters are named after the corresponding variables in the
165distribution's equation, as used in common mathematical practice; most of
166these equations can be found in any statistics text.
167
Tim Peters902446a2001-01-24 23:06:53 +0000168\begin{funcdesc}{random}{}
169 Return the next random floating point number in the range [0.0, 1.0).
170\end{funcdesc}
171
Fred Drake5f0decf2001-01-22 18:18:30 +0000172\begin{funcdesc}{uniform}{a, b}
Tim Peters902446a2001-01-24 23:06:53 +0000173 Return a random real number \var{N} such that
Fred Drake5f0decf2001-01-22 18:18:30 +0000174 \code{\var{a} <= \var{N} < \var{b}}.
175\end{funcdesc}
Fred Drake38e5d272000-04-03 20:13:55 +0000176
Fred Drake2eda4ca1998-03-08 08:13:53 +0000177\begin{funcdesc}{betavariate}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000178 Beta distribution. Conditions on the parameters are
179 \code{\var{alpha} > -1} and \code{\var{beta} > -1}.
180 Returned values range between 0 and 1.
Guido van Rossum571391b1997-04-03 22:41:49 +0000181\end{funcdesc}
182
Guido van Rossum571391b1997-04-03 22:41:49 +0000183\begin{funcdesc}{expovariate}{lambd}
Fred Drake5f0decf2001-01-22 18:18:30 +0000184 Exponential distribution. \var{lambd} is 1.0 divided by the desired
185 mean. (The parameter would be called ``lambda'', but that is a
Tim Peters902446a2001-01-24 23:06:53 +0000186 reserved word in Python.) Returned values range from 0 to
Fred Drake5f0decf2001-01-22 18:18:30 +0000187 positive infinity.
Guido van Rossum571391b1997-04-03 22:41:49 +0000188\end{funcdesc}
189
Raymond Hettinger5359ad62002-05-13 22:40:38 +0000190\begin{funcdesc}{gammavariate}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000191 Gamma distribution. (\emph{Not} the gamma function!) Conditions on
Raymond Hettinger576474c2002-05-13 23:49:13 +0000192 the parameters are \code{\var{alpha} > 0} and \code{\var{beta} > 0}.
Guido van Rossum571391b1997-04-03 22:41:49 +0000193\end{funcdesc}
194
Fred Drake2eda4ca1998-03-08 08:13:53 +0000195\begin{funcdesc}{gauss}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000196 Gaussian distribution. \var{mu} is the mean, and \var{sigma} is the
197 standard deviation. This is slightly faster than the
198 \function{normalvariate()} function defined below.
Guido van Rossum571391b1997-04-03 22:41:49 +0000199\end{funcdesc}
200
Fred Drake2eda4ca1998-03-08 08:13:53 +0000201\begin{funcdesc}{lognormvariate}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000202 Log normal distribution. If you take the natural logarithm of this
203 distribution, you'll get a normal distribution with mean \var{mu}
204 and standard deviation \var{sigma}. \var{mu} can have any value,
Tim Peters902446a2001-01-24 23:06:53 +0000205 and \var{sigma} must be greater than zero.
Guido van Rossum571391b1997-04-03 22:41:49 +0000206\end{funcdesc}
207
Fred Drake2eda4ca1998-03-08 08:13:53 +0000208\begin{funcdesc}{normalvariate}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000209 Normal distribution. \var{mu} is the mean, and \var{sigma} is the
210 standard deviation.
Guido van Rossum571391b1997-04-03 22:41:49 +0000211\end{funcdesc}
212
Fred Drake2eda4ca1998-03-08 08:13:53 +0000213\begin{funcdesc}{vonmisesvariate}{mu, kappa}
Fred Drake5f0decf2001-01-22 18:18:30 +0000214 \var{mu} is the mean angle, expressed in radians between 0 and
215 2*\emph{pi}, and \var{kappa} is the concentration parameter, which
216 must be greater than or equal to zero. If \var{kappa} is equal to
217 zero, this distribution reduces to a uniform random angle over the
218 range 0 to 2*\emph{pi}.
Guido van Rossum571391b1997-04-03 22:41:49 +0000219\end{funcdesc}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000220
Guido van Rossum4f80b651997-12-30 17:38:05 +0000221\begin{funcdesc}{paretovariate}{alpha}
Fred Drake5f0decf2001-01-22 18:18:30 +0000222 Pareto distribution. \var{alpha} is the shape parameter.
Guido van Rossum4f80b651997-12-30 17:38:05 +0000223\end{funcdesc}
224
225\begin{funcdesc}{weibullvariate}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000226 Weibull distribution. \var{alpha} is the scale parameter and
227 \var{beta} is the shape parameter.
Guido van Rossum4f80b651997-12-30 17:38:05 +0000228\end{funcdesc}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000229
Raymond Hettinger40f62172002-12-29 23:03:38 +0000230Alternative Generator
231
232\begin{classdesc}{WichmannHill}{\optional{seed}}
233Class that implements the Wichmann-Hill algorithm as the core generator.
234Has all of the same methods as \class{Random} plus the \method{whseed}
235method described below. Because this class is implemented in pure
236Python, it is not threadsafe and may require locks between calls. The
237period of the generator is 6,953,607,871,644 which is small enough to
238require care that two independent random sequences do not overlap.
239\end{classdesc}
240
241\begin{funcdesc}{whseed}{\optional{x}}
242 This is obsolete, supplied for bit-level compatibility with versions
243 of Python prior to 2.1.
244 See \function{seed} for details. \function{whseed} does not guarantee
245 that distinct integer arguments yield distinct internal states, and can
246 yield no more than about 2**24 distinct internal states in all.
247\end{funcdesc}
Fred Drake065cba12000-12-15 19:07:17 +0000248
Guido van Rossume47da0a1997-07-17 16:34:52 +0000249\begin{seealso}
Raymond Hettinger40f62172002-12-29 23:03:38 +0000250 \seetext{M. Matsumoto and T. Nishimura, ``Mersenne Twister: A
251 623-dimensionally equidistributed uniform pseudorandom
252 number generator'',
253 \citetitle{ACM Transactions on Modeling and Computer Simulation}
254 Vol. 8, No. 1, January pp.3-30 1998.}
255
Tim Peters902446a2001-01-24 23:06:53 +0000256 \seetext{Wichmann, B. A. \& Hill, I. D., ``Algorithm AS 183:
257 An efficient and portable pseudo-random number generator'',
258 \citetitle{Applied Statistics} 31 (1982) 188-190.}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000259\end{seealso}