blob: d60ab799314e4fd57a050b3e026a200f64c4d5e4 [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
Tim Petersd52269b2001-01-25 06:23:18 +000037hidden instance of the \var{random.Random} class. You can instantiate your
38own instances of \var{Random} to get generators that don't share state.
39This is especially useful for multi-threaded programs, creating a different
40instance of \var{Random} for each thread, and using the \method{jumpahead()}
41method to ensure that the generated sequences seen by each thread don't
Tim Peterse360d952001-01-26 10:00:39 +000042overlap (see example below).
43Class \var{Random} can also be subclassed if you want to use a different
44basic generator of your own devising: in that case, override the
Tim Petersd52269b2001-01-25 06:23:18 +000045\method{random()}, \method{seed()}, \method{getstate()},
46\method{setstate()} and \method{jumpahead()} methods.
Tim Petersd7b5e882001-01-25 03:36:26 +000047
Tim Peterse360d952001-01-26 10:00:39 +000048Here's one way to create threadsafe distinct and non-overlapping generators:
49
50\begin{verbatim}
51def create_generators(num, delta, firstseed=None):
52 """Return list of num distinct generators.
53 Each generator has its own unique segment of delta elements
54 from Random.random()'s full period.
55 Seed the first generator with optional arg firstseed (default
56 is None, to seed from current time).
57 """
58
59 from random import Random
60 g = Random(firstseed)
61 result = [g]
62 for i in range(num - 1):
63 laststate = g.getstate()
64 g = Random()
65 g.setstate(laststate)
66 g.jumpahead(delta)
67 result.append(g)
68 return result
69
70gens = create_generators(10, 1000000)
71\end{verbatim}
72
Fred Draked0946da2001-02-01 15:53:24 +000073That creates 10 distinct generators, which can be passed out to 10
74distinct threads. The generators don't share state so can be called
75safely in parallel. So long as no thread calls its \code{g.random()}
76more than a million times (the second argument to
77\function{create_generators()}, the sequences seen by each thread will
78not overlap. The period of the underlying Wichmann-Hill generator
79limits how far this technique can be pushed.
Tim Peterse360d952001-01-26 10:00:39 +000080
Fred Draked0946da2001-02-01 15:53:24 +000081Just for fun, note that since we know the period, \method{jumpahead()}
82can also be used to ``move backward in time:''
Tim Peterse360d952001-01-26 10:00:39 +000083
84\begin{verbatim}
85>>> g = Random(42) # arbitrary
86>>> g.random()
Tim Peters0de88fc2001-02-01 04:59:18 +0000870.25420336316883324
Tim Peterse360d952001-01-26 10:00:39 +000088>>> g.jumpahead(6953607871644L - 1) # move *back* one
89>>> g.random()
Tim Peters0de88fc2001-02-01 04:59:18 +0000900.25420336316883324
Tim Peterse360d952001-01-26 10:00:39 +000091\end{verbatim}
92
Tim Petersd7b5e882001-01-25 03:36:26 +000093
94Bookkeeping functions:
Tim Peters902446a2001-01-24 23:06:53 +000095
96\begin{funcdesc}{seed}{\optional{x}}
97 Initialize the basic random number generator.
Tim Peters0de88fc2001-02-01 04:59:18 +000098 Optional argument \var{x} can be any hashable object.
99 If \var(x) is omitted or \code{None}, current system time is used;
100 current system time is also used to initialize the generator when the
101 module is first imported.
102 If \var(x) is not \code{None} or an int or long,
Fred Draked0946da2001-02-01 15:53:24 +0000103 \code{hash(\var{x})} is used instead.
Tim Peters0de88fc2001-02-01 04:59:18 +0000104 If \var{x} is an int or long, \var{x} is used directly.
105 Distinct values between 0 and 27814431486575L inclusive are guaranteed
106 to yield distinct internal states (this guarantee is specific to the
107 default Wichmann-Hill generator, and may not apply to subclasses
108 supplying their own basic generator).
109\end{funcdesc}
110
111\begin{funcdesc}{whseed}{\optional{x}}
112 This is obsolete, supplied for bit-level compatibility with versions
113 of Python prior to 2.1.
114 See \function{seed} for details. \function{whseed} does not guarantee
115 that distinct integer arguments yield distinct internal states, and can
116 yield no more than about 2**24 distinct internal states in all.
Barry Warsaw83125772001-01-25 00:39:16 +0000117\end{funcdesc}
Guido van Rossum571391b1997-04-03 22:41:49 +0000118
Tim Petersd7b5e882001-01-25 03:36:26 +0000119\begin{funcdesc}{getstate}{}
120 Return an object capturing the current internal state of the generator.
121 This object can be passed to \code{setstate()} to restore the state.
Tim Peters0de88fc2001-02-01 04:59:18 +0000122 \versionadded{2.1}
123\end{funcdesc}
Fred Drake5f0decf2001-01-22 18:18:30 +0000124
Tim Petersd7b5e882001-01-25 03:36:26 +0000125\begin{funcdesc}{setstate}{state}
126 \var{state} should have been obtained from a previous call to
127 \code{getstate()}, and \code{setstate()} restores the internal state
Tim Peters0de88fc2001-02-01 04:59:18 +0000128 of the generator to what it was at the time \code{setstate()} was called.
129 \versionadded{2.1}
Tim Petersd7b5e882001-01-25 03:36:26 +0000130 \end{funcdesc}
131
Tim Petersd52269b2001-01-25 06:23:18 +0000132\begin{funcdesc}{jumpahead}{n}
133 Change the internal state to what it would be if \code{random()} were
134 called n times, but do so quickly. \var{n} is a non-negative integer.
135 This is most useful in multi-threaded programs, in conjuction with
136 multiple instances of the \var{Random} class: \method{setstate()} or
137 \method{seed()} can be used to force all instances into the same
138 internal state, and then \method{jumpahead()} can be used to force the
139 instances' states as far apart as you like (up to the period of the
140 generator).
Tim Peters0de88fc2001-02-01 04:59:18 +0000141 \versionadded{2.1}
Tim Petersd52269b2001-01-25 06:23:18 +0000142 \end{funcdesc}
Tim Petersd7b5e882001-01-25 03:36:26 +0000143
144Functions for integers:
Fred Drake5f0decf2001-01-22 18:18:30 +0000145
Fred Drake5f0decf2001-01-22 18:18:30 +0000146\begin{funcdesc}{randrange}{\optional{start,} stop\optional{, step}}
147 Return a randomly selected element from \code{range(\var{start},
148 \var{stop}, \var{step})}. This is equivalent to
Tim Peters902446a2001-01-24 23:06:53 +0000149 \code{choice(range(\var{start}, \var{stop}, \var{step}))},
150 but doesn't actually build a range object.
Fred Drake5f0decf2001-01-22 18:18:30 +0000151 \versionadded{1.5.2}
152\end{funcdesc}
153
Tim Petersd7b5e882001-01-25 03:36:26 +0000154\begin{funcdesc}{randint}{a, b}
155 \deprecated{2.0}{Use \function{randrange()} instead.}
156 Return a random integer \var{N} such that
157 \code{\var{a} <= \var{N} <= \var{b}}.
158\end{funcdesc}
159
160
161Functions for sequences:
162
163\begin{funcdesc}{choice}{seq}
164 Return a random element from the non-empty sequence \var{seq}.
165\end{funcdesc}
166
167\begin{funcdesc}{shuffle}{x\optional{, random}}
168 Shuffle the sequence \var{x} in place.
169 The optional argument \var{random} is a 0-argument function
170 returning a random float in [0.0, 1.0); by default, this is the
171 function \function{random()}.
172
173 Note that for even rather small \code{len(\var{x})}, the total
174 number of permutations of \var{x} is larger than the period of most
175 random number generators; this implies that most permutations of a
176 long sequence can never be generated.
177\end{funcdesc}
178
179
180The following functions generate specific real-valued distributions.
181Function parameters are named after the corresponding variables in the
182distribution's equation, as used in common mathematical practice; most of
183these equations can be found in any statistics text.
184
Tim Peters902446a2001-01-24 23:06:53 +0000185\begin{funcdesc}{random}{}
186 Return the next random floating point number in the range [0.0, 1.0).
187\end{funcdesc}
188
Fred Drake5f0decf2001-01-22 18:18:30 +0000189\begin{funcdesc}{uniform}{a, b}
Tim Peters902446a2001-01-24 23:06:53 +0000190 Return a random real number \var{N} such that
Fred Drake5f0decf2001-01-22 18:18:30 +0000191 \code{\var{a} <= \var{N} < \var{b}}.
192\end{funcdesc}
Fred Drake38e5d272000-04-03 20:13:55 +0000193
Fred Drake2eda4ca1998-03-08 08:13:53 +0000194\begin{funcdesc}{betavariate}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000195 Beta distribution. Conditions on the parameters are
196 \code{\var{alpha} > -1} and \code{\var{beta} > -1}.
197 Returned values range between 0 and 1.
Guido van Rossum571391b1997-04-03 22:41:49 +0000198\end{funcdesc}
199
Fred Drake2eda4ca1998-03-08 08:13:53 +0000200\begin{funcdesc}{cunifvariate}{mean, arc}
Fred Drake5f0decf2001-01-22 18:18:30 +0000201 Circular uniform distribution. \var{mean} is the mean angle, and
202 \var{arc} is the range of the distribution, centered around the mean
203 angle. Both values must be expressed in radians, and can range
Tim Peters902446a2001-01-24 23:06:53 +0000204 between 0 and \emph{pi}. Returned values range between
Fred Drake5f0decf2001-01-22 18:18:30 +0000205 \code{\var{mean} - \var{arc}/2} and \code{\var{mean} +
206 \var{arc}/2}.
Guido van Rossum571391b1997-04-03 22:41:49 +0000207\end{funcdesc}
208
209\begin{funcdesc}{expovariate}{lambd}
Fred Drake5f0decf2001-01-22 18:18:30 +0000210 Exponential distribution. \var{lambd} is 1.0 divided by the desired
211 mean. (The parameter would be called ``lambda'', but that is a
Tim Peters902446a2001-01-24 23:06:53 +0000212 reserved word in Python.) Returned values range from 0 to
Fred Drake5f0decf2001-01-22 18:18:30 +0000213 positive infinity.
Guido van Rossum571391b1997-04-03 22:41:49 +0000214\end{funcdesc}
215
Fred Drake2eda4ca1998-03-08 08:13:53 +0000216\begin{funcdesc}{gamma}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000217 Gamma distribution. (\emph{Not} the gamma function!) Conditions on
218 the parameters are \code{\var{alpha} > -1} and \code{\var{beta} > 0}.
Guido van Rossum571391b1997-04-03 22:41:49 +0000219\end{funcdesc}
220
Fred Drake2eda4ca1998-03-08 08:13:53 +0000221\begin{funcdesc}{gauss}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000222 Gaussian distribution. \var{mu} is the mean, and \var{sigma} is the
223 standard deviation. This is slightly faster than the
224 \function{normalvariate()} function defined below.
Guido van Rossum571391b1997-04-03 22:41:49 +0000225\end{funcdesc}
226
Fred Drake2eda4ca1998-03-08 08:13:53 +0000227\begin{funcdesc}{lognormvariate}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000228 Log normal distribution. If you take the natural logarithm of this
229 distribution, you'll get a normal distribution with mean \var{mu}
230 and standard deviation \var{sigma}. \var{mu} can have any value,
Tim Peters902446a2001-01-24 23:06:53 +0000231 and \var{sigma} must be greater than zero.
Guido van Rossum571391b1997-04-03 22:41:49 +0000232\end{funcdesc}
233
Fred Drake2eda4ca1998-03-08 08:13:53 +0000234\begin{funcdesc}{normalvariate}{mu, sigma}
Fred Drake5f0decf2001-01-22 18:18:30 +0000235 Normal distribution. \var{mu} is the mean, and \var{sigma} is the
236 standard deviation.
Guido van Rossum571391b1997-04-03 22:41:49 +0000237\end{funcdesc}
238
Fred Drake2eda4ca1998-03-08 08:13:53 +0000239\begin{funcdesc}{vonmisesvariate}{mu, kappa}
Fred Drake5f0decf2001-01-22 18:18:30 +0000240 \var{mu} is the mean angle, expressed in radians between 0 and
241 2*\emph{pi}, and \var{kappa} is the concentration parameter, which
242 must be greater than or equal to zero. If \var{kappa} is equal to
243 zero, this distribution reduces to a uniform random angle over the
244 range 0 to 2*\emph{pi}.
Guido van Rossum571391b1997-04-03 22:41:49 +0000245\end{funcdesc}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000246
Guido van Rossum4f80b651997-12-30 17:38:05 +0000247\begin{funcdesc}{paretovariate}{alpha}
Fred Drake5f0decf2001-01-22 18:18:30 +0000248 Pareto distribution. \var{alpha} is the shape parameter.
Guido van Rossum4f80b651997-12-30 17:38:05 +0000249\end{funcdesc}
250
251\begin{funcdesc}{weibullvariate}{alpha, beta}
Fred Drake5f0decf2001-01-22 18:18:30 +0000252 Weibull distribution. \var{alpha} is the scale parameter and
253 \var{beta} is the shape parameter.
Guido van Rossum4f80b651997-12-30 17:38:05 +0000254\end{funcdesc}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000255
Fred Drake065cba12000-12-15 19:07:17 +0000256
Guido van Rossume47da0a1997-07-17 16:34:52 +0000257\begin{seealso}
Tim Peters902446a2001-01-24 23:06:53 +0000258 \seetext{Wichmann, B. A. \& Hill, I. D., ``Algorithm AS 183:
259 An efficient and portable pseudo-random number generator'',
260 \citetitle{Applied Statistics} 31 (1982) 188-190.}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000261\end{seealso}