Apparently the code to forestall Tk eating events was too aggressive (Tk user input...
[python/dscho.git] / Doc / lib / librandom.tex
blob69932604bf20a9f70c8238564081c9702ce929c4
1 \section{\module{random} ---
2 Generate pseudo-random numbers}
4 \declaremodule{standard}{random}
5 \modulesynopsis{Generate pseudo-random numbers with various common
6 distributions.}
9 This module implements pseudo-random number generators for various
10 distributions.
11 For integers, uniform selection from a range.
12 For sequences, uniform selection of a random element, and a function to
13 generate a random permutation of a list in-place.
14 On the real line, there are functions to compute uniform, normal (Gaussian),
15 lognormal, negative exponential, gamma, and beta distributions.
16 For generating distribution of angles, the circular uniform and
17 von Mises distributions are available.
19 Almost all module functions depend on the basic function
20 \function{random()}, which generates a random float uniformly in
21 the semi-open range [0.0, 1.0). Python uses the standard Wichmann-Hill
22 generator, combining three pure multiplicative congruential
23 generators of modulus 30269, 30307 and 30323. Its period (how many
24 numbers it generates before repeating the sequence exactly) is
25 6,953,607,871,644. While of much higher quality than the \function{rand()}
26 function supplied by most C libraries, the theoretical properties
27 are much the same as for a single linear congruential generator of
28 large modulus. It is not suitable for all purposes, and is completely
29 unsuitable for cryptographic purposes.
31 The functions in this module are not threadsafe: if you want to call these
32 functions from multiple threads, you should explicitly serialize the calls.
33 Else, because no critical sections are implemented internally, calls
34 from different threads may see the same return values.
36 The functions supplied by this module are actually bound methods of a
37 hidden instance of the \class{random.Random} class. You can
38 instantiate your own instances of \class{Random} to get generators
39 that don't share state. This is especially useful for multi-threaded
40 programs, creating a different instance of \class{Random} for each
41 thread, and using the \method{jumpahead()} method to ensure that the
42 generated sequences seen by each thread don't overlap (see example
43 below).
45 Class \class{Random} can also be subclassed if you want to use a
46 different basic generator of your own devising: in that case, override
47 the \method{random()}, \method{seed()}, \method{getstate()},
48 \method{setstate()} and \method{jumpahead()} methods.
50 Here's one way to create threadsafe distinct and non-overlapping generators:
52 \begin{verbatim}
53 def 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 """
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
72 gens = create_generators(10, 1000000)
73 \end{verbatim}
75 That creates 10 distinct generators, which can be passed out to 10
76 distinct threads. The generators don't share state so can be called
77 safely in parallel. So long as no thread calls its \code{g.random()}
78 more than a million times (the second argument to
79 \function{create_generators()}, the sequences seen by each thread will
80 not overlap. The period of the underlying Wichmann-Hill generator
81 limits how far this technique can be pushed.
83 Just for fun, note that since we know the period, \method{jumpahead()}
84 can also be used to ``move backward in time:''
86 \begin{verbatim}
87 >>> g = Random(42) # arbitrary
88 >>> g.random()
89 0.25420336316883324
90 >>> g.jumpahead(6953607871644L - 1) # move *back* one
91 >>> g.random()
92 0.25420336316883324
93 \end{verbatim}
96 Bookkeeping functions:
98 \begin{funcdesc}{seed}{\optional{x}}
99 Initialize the basic random number generator.
100 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,
105 \code{hash(\var{x})} is used instead.
106 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}
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.
119 \end{funcdesc}
121 \begin{funcdesc}{getstate}{}
122 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.
125 \versionadded{2.1}
126 \end{funcdesc}
128 \begin{funcdesc}{setstate}{state}
129 \var{state} should have been obtained from a previous call to
130 \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.
133 \versionadded{2.1}
134 \end{funcdesc}
136 \begin{funcdesc}{jumpahead}{n}
137 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 \class{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).
145 \versionadded{2.1}
146 \end{funcdesc}
148 Functions for integers:
150 \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
153 \code{choice(range(\var{start}, \var{stop}, \var{step}))},
154 but doesn't actually build a range object.
155 \versionadded{1.5.2}
156 \end{funcdesc}
158 \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}
165 Functions for sequences:
167 \begin{funcdesc}{choice}{seq}
168 Return a random element from the non-empty sequence \var{seq}.
169 \end{funcdesc}
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()}.
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}
184 The following functions generate specific real-valued distributions.
185 Function parameters are named after the corresponding variables in the
186 distribution's equation, as used in common mathematical practice; most of
187 these equations can be found in any statistics text.
189 \begin{funcdesc}{random}{}
190 Return the next random floating point number in the range [0.0, 1.0).
191 \end{funcdesc}
193 \begin{funcdesc}{uniform}{a, b}
194 Return a random real number \var{N} such that
195 \code{\var{a} <= \var{N} < \var{b}}.
196 \end{funcdesc}
198 \begin{funcdesc}{betavariate}{alpha, beta}
199 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.
202 \end{funcdesc}
204 \begin{funcdesc}{cunifvariate}{mean, arc}
205 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
208 between 0 and \emph{pi}. Returned values range between
209 \code{\var{mean} - \var{arc}/2} and \code{\var{mean} +
210 \var{arc}/2}.
211 \end{funcdesc}
213 \begin{funcdesc}{expovariate}{lambd}
214 Exponential distribution. \var{lambd} is 1.0 divided by the desired
215 mean. (The parameter would be called ``lambda'', but that is a
216 reserved word in Python.) Returned values range from 0 to
217 positive infinity.
218 \end{funcdesc}
220 \begin{funcdesc}{gamma}{alpha, beta}
221 Gamma distribution. (\emph{Not} the gamma function!) Conditions on
222 the parameters are \code{\var{alpha} > -1} and \code{\var{beta} > 0}.
223 \end{funcdesc}
225 \begin{funcdesc}{gauss}{mu, sigma}
226 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.
229 \end{funcdesc}
231 \begin{funcdesc}{lognormvariate}{mu, sigma}
232 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,
235 and \var{sigma} must be greater than zero.
236 \end{funcdesc}
238 \begin{funcdesc}{normalvariate}{mu, sigma}
239 Normal distribution. \var{mu} is the mean, and \var{sigma} is the
240 standard deviation.
241 \end{funcdesc}
243 \begin{funcdesc}{vonmisesvariate}{mu, kappa}
244 \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}.
249 \end{funcdesc}
251 \begin{funcdesc}{paretovariate}{alpha}
252 Pareto distribution. \var{alpha} is the shape parameter.
253 \end{funcdesc}
255 \begin{funcdesc}{weibullvariate}{alpha, beta}
256 Weibull distribution. \var{alpha} is the scale parameter and
257 \var{beta} is the shape parameter.
258 \end{funcdesc}
261 \begin{seealso}
262 \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.}
265 \end{seealso}