blob: e2e24e128d8f0e1e873e414f5045b6027028762d [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.
11For integers, uniform selection from a range.
12For sequences, uniform selection of a random element, and a function to
13generate a random permutation of a list in-place.
14On the real line, there are functions to compute uniform, normal (Gaussian),
15lognormal, negative exponential, gamma, and beta distributions.
16For generating distribution of angles, the circular uniform and
17von Mises distributions are available.
Guido van Rossum571391b1997-04-03 22:41:49 +000018
Tim Peters902446a2001-01-24 23:06:53 +000019Almost all module functions depend on the basic function
20\function{random()}, which generates a random float uniformly in
21the semi-open range [0.0, 1.0). Python uses the standard Wichmann-Hill
22generator, combining three pure multiplicative congruential
23generators of modulus 30269, 30307 and 30323. Its period (how many
24numbers it generates before repeating the sequence exactly) is
256,953,607,871,644. While of much higher quality than the \function{rand()}
26function supplied by most C libraries, the theoretical properties
27are much the same as for a single linear congruential generator of
Tim Peters0de88fc2001-02-01 04:59:18 +000028large modulus. It is not suitable for all purposes, and is completely
29unsuitable for cryptographic purposes.
Tim Peters902446a2001-01-24 23:06:53 +000030
31The functions in this module are not threadsafe: if you want to call these
32functions from multiple threads, you should explicitly serialize the calls.
33Else, because no critical sections are implemented internally, calls
34from different threads may see the same return values.
35
Tim Petersd7b5e882001-01-25 03:36:26 +000036The functions supplied by this module are actually bound methods of a
Fred Drake844bd5b2001-02-02 02:42:31 +000037hidden instance of the \class{random.Random} class. You can
38instantiate your own instances of \class{Random} to get generators
39that don't share state. This is especially useful for multi-threaded
40programs, creating a different instance of \class{Random} for each
41thread, and using the \method{jumpahead()} method to ensure that the
42generated sequences seen by each thread don't overlap (see example
43below).
44
45Class \class{Random} can also be subclassed if you want to use a
46different basic generator of your own devising: in that case, override
47the \method{random()}, \method{seed()}, \method{getstate()},
Tim Petersd52269b2001-01-25 06:23:18 +000048\method{setstate()} and \method{jumpahead()} methods.
Tim Petersd7b5e882001-01-25 03:36:26 +000049
Tim Peterse360d952001-01-26 10:00:39 +000050Here's one way to create threadsafe distinct and non-overlapping generators:
51
52\begin{verbatim}
53def create_generators(num, delta, firstseed=None):
54 """Return list of num distinct generators.
55 Each generator has its own unique segment of delta elements
56 from Random.random()'s full period.
57 Seed the first generator with optional arg firstseed (default
58 is None, to seed from current time).
59 """
60
61 from random import Random
62 g = Random(firstseed)
63 result = [g]
64 for i in range(num - 1):
65 laststate = g.getstate()
66 g = Random()
67 g.setstate(laststate)
68 g.jumpahead(delta)
69 result.append(g)
70 return result
71
72gens = create_generators(10, 1000000)
73\end{verbatim}
74
Fred Draked0946da2001-02-01 15:53:24 +000075That creates 10 distinct generators, which can be passed out to 10
76distinct threads. The generators don't share state so can be called
77safely in parallel. So long as no thread calls its \code{g.random()}
78more than a million times (the second argument to
79\function{create_generators()}, the sequences seen by each thread will
80not overlap. The period of the underlying Wichmann-Hill generator
81limits how far this technique can be pushed.
Tim Peterse360d952001-01-26 10:00:39 +000082
Fred Draked0946da2001-02-01 15:53:24 +000083Just for fun, note that since we know the period, \method{jumpahead()}
84can also be used to ``move backward in time:''
Tim Peterse360d952001-01-26 10:00:39 +000085
86\begin{verbatim}
87>>> g = Random(42) # arbitrary
88>>> g.random()
Tim Peters0de88fc2001-02-01 04:59:18 +0000890.25420336316883324
Tim Peterse360d952001-01-26 10:00:39 +000090>>> g.jumpahead(6953607871644L - 1) # move *back* one
91>>> g.random()
Tim Peters0de88fc2001-02-01 04:59:18 +0000920.25420336316883324
Tim Peterse360d952001-01-26 10:00:39 +000093\end{verbatim}
94
Tim Petersd7b5e882001-01-25 03:36:26 +000095
96Bookkeeping functions:
Tim Peters902446a2001-01-24 23:06:53 +000097
98\begin{funcdesc}{seed}{\optional{x}}
99 Initialize the basic random number generator.
Tim Peters0de88fc2001-02-01 04:59:18 +0000100 Optional argument \var{x} can be any hashable object.
101 If \var(x) is omitted or \code{None}, current system time is used;
102 current system time is also used to initialize the generator when the
103 module is first imported.
104 If \var(x) is not \code{None} or an int or long,
Fred Draked0946da2001-02-01 15:53:24 +0000105 \code{hash(\var{x})} is used instead.
Tim Peters0de88fc2001-02-01 04:59:18 +0000106 If \var{x} is an int or long, \var{x} is used directly.
107 Distinct values between 0 and 27814431486575L inclusive are guaranteed
108 to yield distinct internal states (this guarantee is specific to the
109 default Wichmann-Hill generator, and may not apply to subclasses
110 supplying their own basic generator).
111\end{funcdesc}
112
113\begin{funcdesc}{whseed}{\optional{x}}
114 This is obsolete, supplied for bit-level compatibility with versions
115 of Python prior to 2.1.
116 See \function{seed} for details. \function{whseed} does not guarantee
117 that distinct integer arguments yield distinct internal states, and can
118 yield no more than about 2**24 distinct internal states in all.
Barry Warsaw83125772001-01-25 00:39:16 +0000119\end{funcdesc}
Guido van Rossum571391b1997-04-03 22:41:49 +0000120
Tim Petersd7b5e882001-01-25 03:36:26 +0000121\begin{funcdesc}{getstate}{}
Fred Drake844bd5b2001-02-02 02:42:31 +0000122 Return an object capturing the current internal state of the
123 generator. This object can be passed to \function{setstate()} to
124 restore the state.
Tim Peters0de88fc2001-02-01 04:59:18 +0000125 \versionadded{2.1}
126\end{funcdesc}
Fred Drake5f0decf2001-01-22 18:18:30 +0000127
Tim Petersd7b5e882001-01-25 03:36:26 +0000128\begin{funcdesc}{setstate}{state}
129 \var{state} should have been obtained from a previous call to
Fred Drake844bd5b2001-02-02 02:42:31 +0000130 \function{getstate()}, and \function{setstate()} restores the
131 internal state of the generator to what it was at the time
132 \function{setstate()} was called.
Tim Peters0de88fc2001-02-01 04:59:18 +0000133 \versionadded{2.1}
Fred Drake844bd5b2001-02-02 02:42:31 +0000134\end{funcdesc}
Tim Petersd7b5e882001-01-25 03:36:26 +0000135
Tim Petersd52269b2001-01-25 06:23:18 +0000136\begin{funcdesc}{jumpahead}{n}
Fred Drake844bd5b2001-02-02 02:42:31 +0000137 Change the internal state to what it would be if \function{random()}
138 were called \var{n} times, but do so quickly. \var{n} is a
139 non-negative integer. This is most useful in multi-threaded
140 programs, in conjuction with multiple instances of the \var{Random}
141 class: \method{setstate()} or \method{seed()} can be used to force
142 all instances into the same internal state, and then
143 \method{jumpahead()} can be used to force the instances' states as
144 far apart as you like (up to the period of the generator).
Tim Peters0de88fc2001-02-01 04:59:18 +0000145 \versionadded{2.1}
Tim Petersd52269b2001-01-25 06:23:18 +0000146 \end{funcdesc}
Tim Petersd7b5e882001-01-25 03:36:26 +0000147
148Functions for integers:
Fred Drake5f0decf2001-01-22 18:18:30 +0000149
Fred Drake5f0decf2001-01-22 18:18:30 +0000150\begin{funcdesc}{randrange}{\optional{start,} stop\optional{, step}}
151 Return a randomly selected element from \code{range(\var{start},
152 \var{stop}, \var{step})}. This is equivalent to
Tim Peters902446a2001-01-24 23:06:53 +0000153 \code{choice(range(\var{start}, \var{stop}, \var{step}))},
154 but doesn't actually build a range object.
Fred Drake5f0decf2001-01-22 18:18:30 +0000155 \versionadded{1.5.2}
156\end{funcdesc}
157
Tim Petersd7b5e882001-01-25 03:36:26 +0000158\begin{funcdesc}{randint}{a, b}
159 \deprecated{2.0}{Use \function{randrange()} instead.}
160 Return a random integer \var{N} such that
161 \code{\var{a} <= \var{N} <= \var{b}}.
162\end{funcdesc}
163
164
165Functions for sequences:
166
167\begin{funcdesc}{choice}{seq}
168 Return a random element from the non-empty sequence \var{seq}.
169\end{funcdesc}
170
171\begin{funcdesc}{shuffle}{x\optional{, random}}
172 Shuffle the sequence \var{x} in place.
173 The optional argument \var{random} is a 0-argument function
174 returning a random float in [0.0, 1.0); by default, this is the
175 function \function{random()}.
176
177 Note that for even rather small \code{len(\var{x})}, the total
178 number of permutations of \var{x} is larger than the period of most
179 random number generators; this implies that most permutations of a
180 long sequence can never be generated.
181\end{funcdesc}
182
183
184The following functions generate specific real-valued distributions.
185Function parameters are named after the corresponding variables in the
186distribution's equation, as used in common mathematical practice; most of
187these equations can be found in any statistics text.
188
Tim Peters902446a2001-01-24 23:06:53 +0000189\begin{funcdesc}{random}{}
190 Return the next random floating point number in the range [0.0, 1.0).
191\end{funcdesc}
192
Fred Drake5f0decf2001-01-22 18:18:30 +0000193\begin{funcdesc}{uniform}{a, b}
Tim Peters902446a2001-01-24 23:06:53 +0000194 Return a random real number \var{N} such that
Fred Drake5f0decf2001-01-22 18:18:30 +0000195 \code{\var{a} <= \var{N} < \var{b}}.
196\end{funcdesc}
Fred Drake38e5d272000-04-03 20:13:55 +0000197
Fred Drake2eda4ca1998-03-08 08:13:53 +0000198\begin{funcdesc}{betavariate}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000199 Beta distribution. Conditions on the parameters are
200 \code{\var{alpha} > -1} and \code{\var{beta} > -1}.
201 Returned values range between 0 and 1.
Guido van Rossum571391b1997-04-03 22:41:49 +0000202\end{funcdesc}
203
Fred Drake2eda4ca1998-03-08 08:13:53 +0000204\begin{funcdesc}{cunifvariate}{mean, arc}
Fred Drake5f0decf2001-01-22 18:18:30 +0000205 Circular uniform distribution. \var{mean} is the mean angle, and
206 \var{arc} is the range of the distribution, centered around the mean
207 angle. Both values must be expressed in radians, and can range
Tim Peters902446a2001-01-24 23:06:53 +0000208 between 0 and \emph{pi}. Returned values range between
Fred Drake5f0decf2001-01-22 18:18:30 +0000209 \code{\var{mean} - \var{arc}/2} and \code{\var{mean} +
210 \var{arc}/2}.
Guido van Rossum571391b1997-04-03 22:41:49 +0000211\end{funcdesc}
212
213\begin{funcdesc}{expovariate}{lambd}
Fred Drake5f0decf2001-01-22 18:18:30 +0000214 Exponential distribution. \var{lambd} is 1.0 divided by the desired
215 mean. (The parameter would be called ``lambda'', but that is a
Tim Peters902446a2001-01-24 23:06:53 +0000216 reserved word in Python.) Returned values range from 0 to
Fred Drake5f0decf2001-01-22 18:18:30 +0000217 positive infinity.
Guido van Rossum571391b1997-04-03 22:41:49 +0000218\end{funcdesc}
219
Fred Drake2eda4ca1998-03-08 08:13:53 +0000220\begin{funcdesc}{gamma}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000221 Gamma distribution. (\emph{Not} the gamma function!) Conditions on
222 the parameters are \code{\var{alpha} > -1} and \code{\var{beta} > 0}.
Guido van Rossum571391b1997-04-03 22:41:49 +0000223\end{funcdesc}
224
Fred Drake2eda4ca1998-03-08 08:13:53 +0000225\begin{funcdesc}{gauss}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000226 Gaussian distribution. \var{mu} is the mean, and \var{sigma} is the
227 standard deviation. This is slightly faster than the
228 \function{normalvariate()} function defined below.
Guido van Rossum571391b1997-04-03 22:41:49 +0000229\end{funcdesc}
230
Fred Drake2eda4ca1998-03-08 08:13:53 +0000231\begin{funcdesc}{lognormvariate}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000232 Log normal distribution. If you take the natural logarithm of this
233 distribution, you'll get a normal distribution with mean \var{mu}
234 and standard deviation \var{sigma}. \var{mu} can have any value,
Tim Peters902446a2001-01-24 23:06:53 +0000235 and \var{sigma} must be greater than zero.
Guido van Rossum571391b1997-04-03 22:41:49 +0000236\end{funcdesc}
237
Fred Drake2eda4ca1998-03-08 08:13:53 +0000238\begin{funcdesc}{normalvariate}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000239 Normal distribution. \var{mu} is the mean, and \var{sigma} is the
240 standard deviation.
Guido van Rossum571391b1997-04-03 22:41:49 +0000241\end{funcdesc}
242
Fred Drake2eda4ca1998-03-08 08:13:53 +0000243\begin{funcdesc}{vonmisesvariate}{mu, kappa}
Fred Drake5f0decf2001-01-22 18:18:30 +0000244 \var{mu} is the mean angle, expressed in radians between 0 and
245 2*\emph{pi}, and \var{kappa} is the concentration parameter, which
246 must be greater than or equal to zero. If \var{kappa} is equal to
247 zero, this distribution reduces to a uniform random angle over the
248 range 0 to 2*\emph{pi}.
Guido van Rossum571391b1997-04-03 22:41:49 +0000249\end{funcdesc}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000250
Guido van Rossum4f80b651997-12-30 17:38:05 +0000251\begin{funcdesc}{paretovariate}{alpha}
Fred Drake5f0decf2001-01-22 18:18:30 +0000252 Pareto distribution. \var{alpha} is the shape parameter.
Guido van Rossum4f80b651997-12-30 17:38:05 +0000253\end{funcdesc}
254
255\begin{funcdesc}{weibullvariate}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000256 Weibull distribution. \var{alpha} is the scale parameter and
257 \var{beta} is the shape parameter.
Guido van Rossum4f80b651997-12-30 17:38:05 +0000258\end{funcdesc}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000259
Fred Drake065cba12000-12-15 19:07:17 +0000260
Guido van Rossume47da0a1997-07-17 16:34:52 +0000261\begin{seealso}
Tim Peters902446a2001-01-24 23:06:53 +0000262 \seetext{Wichmann, B. A. \& Hill, I. D., ``Algorithm AS 183:
263 An efficient and portable pseudo-random number generator'',
264 \citetitle{Applied Statistics} 31 (1982) 188-190.}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000265\end{seealso}