blob: f919718a6db012725a2f8b485e574e4749edf697 [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Random variable generators.
Guido van Rossumff03b1a1994-03-09 12:55:02 +00002
Tim Petersd7b5e882001-01-25 03:36:26 +00003 integers
4 --------
5 uniform within range
6
7 sequences
8 ---------
9 pick random element
Raymond Hettingerf24eb352002-11-12 17:41:57 +000010 pick random sample
Tim Petersd7b5e882001-01-25 03:36:26 +000011 generate random permutation
12
Guido van Rossume7b146f2000-02-04 15:28:42 +000013 distributions on the real line:
14 ------------------------------
Tim Petersd7b5e882001-01-25 03:36:26 +000015 uniform
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +000016 triangular
Guido van Rossume7b146f2000-02-04 15:28:42 +000017 normal (Gaussian)
18 lognormal
19 negative exponential
20 gamma
21 beta
Raymond Hettinger40f62172002-12-29 23:03:38 +000022 pareto
23 Weibull
Guido van Rossumff03b1a1994-03-09 12:55:02 +000024
Guido van Rossume7b146f2000-02-04 15:28:42 +000025 distributions on the circle (angles 0 to 2pi)
26 ---------------------------------------------
27 circular uniform
28 von Mises
29
Raymond Hettinger40f62172002-12-29 23:03:38 +000030General notes on the underlying Mersenne Twister core generator:
Guido van Rossume7b146f2000-02-04 15:28:42 +000031
Raymond Hettinger40f62172002-12-29 23:03:38 +000032* The period is 2**19937-1.
Tim Peters0e115952006-06-10 22:51:45 +000033* It is one of the most extensively tested generators in existence.
34* Without a direct way to compute N steps forward, the semantics of
35 jumpahead(n) are weakened to simply jump to another distant state and rely
36 on the large period to avoid overlapping sequences.
37* The random() method is implemented in C, executes in a single Python step,
38 and is, therefore, threadsafe.
Tim Peterse360d952001-01-26 10:00:39 +000039
Guido van Rossume7b146f2000-02-04 15:28:42 +000040"""
Guido van Rossumd03e1191998-05-29 17:51:31 +000041
Raymond Hettingerc4f7bab2008-03-23 19:37:53 +000042from __future__ import division
Raymond Hettinger2f726e92003-10-05 09:09:15 +000043from warnings import warn as _warn
44from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType
Raymond Hettinger91e27c22005-08-19 01:36:35 +000045from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
Tim Petersd7b5e882001-01-25 03:36:26 +000046from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +000047from os import urandom as _urandom
48from binascii import hexlify as _hexlify
Guido van Rossumff03b1a1994-03-09 12:55:02 +000049
Raymond Hettingerf24eb352002-11-12 17:41:57 +000050__all__ = ["Random","seed","random","uniform","randint","choice","sample",
Skip Montanaro0de65802001-02-15 22:15:14 +000051 "randrange","shuffle","normalvariate","lognormvariate",
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +000052 "expovariate","vonmisesvariate","gammavariate","triangular",
Raymond Hettingerf8a52d32003-08-05 12:23:19 +000053 "gauss","betavariate","paretovariate","weibullvariate",
Raymond Hettinger356a4592004-08-30 06:14:31 +000054 "getstate","setstate","jumpahead", "WichmannHill", "getrandbits",
Raymond Hettinger23f12412004-09-13 22:23:21 +000055 "SystemRandom"]
Tim Petersd7b5e882001-01-25 03:36:26 +000056
57NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
Tim Petersd7b5e882001-01-25 03:36:26 +000058TWOPI = 2.0*_pi
Tim Petersd7b5e882001-01-25 03:36:26 +000059LOG4 = _log(4.0)
Tim Petersd7b5e882001-01-25 03:36:26 +000060SG_MAGICCONST = 1.0 + _log(4.5)
Raymond Hettinger2f726e92003-10-05 09:09:15 +000061BPF = 53 # Number of bits in a float
Tim Peters7c2a85b2004-08-31 02:19:55 +000062RECIP_BPF = 2**-BPF
Tim Petersd7b5e882001-01-25 03:36:26 +000063
Raymond Hettinger356a4592004-08-30 06:14:31 +000064
Tim Petersd7b5e882001-01-25 03:36:26 +000065# Translated by Guido van Rossum from C source provided by
Raymond Hettinger40f62172002-12-29 23:03:38 +000066# Adrian Baddeley. Adapted by Raymond Hettinger for use with
Raymond Hettinger3fa19d72004-08-31 01:05:15 +000067# the Mersenne Twister and os.urandom() core generators.
Tim Petersd7b5e882001-01-25 03:36:26 +000068
Raymond Hettinger145a4a02003-01-07 10:25:55 +000069import _random
Raymond Hettinger40f62172002-12-29 23:03:38 +000070
Raymond Hettinger145a4a02003-01-07 10:25:55 +000071class Random(_random.Random):
Raymond Hettingerc32f0332002-05-23 19:44:49 +000072 """Random number generator base class used by bound module functions.
73
74 Used to instantiate instances of Random to get generators that don't
75 share state. Especially useful for multi-threaded programs, creating
76 a different instance of Random for each thread, and using the jumpahead()
77 method to ensure that the generated sequences seen by each thread don't
78 overlap.
79
80 Class Random can also be subclassed if you want to use a different basic
81 generator of your own devising: in that case, override the following
Benjamin Petersonf2eb2b42008-07-30 13:46:53 +000082 methods: random(), seed(), getstate(), setstate() and jumpahead().
83 Optionally, implement a getrandbits() method so that randrange() can cover
84 arbitrarily large ranges.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +000085
Raymond Hettingerc32f0332002-05-23 19:44:49 +000086 """
Tim Petersd7b5e882001-01-25 03:36:26 +000087
Martin v. Löwis6b449f42007-12-03 19:20:02 +000088 VERSION = 3 # used by getstate/setstate
Tim Petersd7b5e882001-01-25 03:36:26 +000089
90 def __init__(self, x=None):
91 """Initialize an instance.
92
93 Optional argument x controls seeding, as for Random.seed().
94 """
95
96 self.seed(x)
Raymond Hettinger40f62172002-12-29 23:03:38 +000097 self.gauss_next = None
Tim Petersd7b5e882001-01-25 03:36:26 +000098
Tim Peters0de88fc2001-02-01 04:59:18 +000099 def seed(self, a=None):
100 """Initialize internal state from hashable object.
Tim Petersd7b5e882001-01-25 03:36:26 +0000101
Raymond Hettinger23f12412004-09-13 22:23:21 +0000102 None or no argument seeds from current time or from an operating
103 system specific randomness source if available.
Tim Peters0de88fc2001-02-01 04:59:18 +0000104
Tim Petersbcd725f2001-02-01 10:06:53 +0000105 If a is not None or an int or long, hash(a) is used instead.
Tim Petersd7b5e882001-01-25 03:36:26 +0000106 """
107
Raymond Hettinger3081d592003-08-09 18:30:57 +0000108 if a is None:
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000109 try:
110 a = long(_hexlify(_urandom(16)), 16)
111 except NotImplementedError:
Raymond Hettinger356a4592004-08-30 06:14:31 +0000112 import time
113 a = long(time.time() * 256) # use fractional seconds
Raymond Hettinger356a4592004-08-30 06:14:31 +0000114
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000115 super(Random, self).seed(a)
Tim Peters46c04e12002-05-05 20:40:00 +0000116 self.gauss_next = None
117
Tim Peterscd804102001-01-25 20:25:57 +0000118 def getstate(self):
119 """Return internal state; can be passed to setstate() later."""
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000120 return self.VERSION, super(Random, self).getstate(), self.gauss_next
Tim Peterscd804102001-01-25 20:25:57 +0000121
122 def setstate(self, state):
123 """Restore internal state from object returned by getstate()."""
124 version = state[0]
Martin v. Löwis6b449f42007-12-03 19:20:02 +0000125 if version == 3:
Raymond Hettinger40f62172002-12-29 23:03:38 +0000126 version, internalstate, self.gauss_next = state
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000127 super(Random, self).setstate(internalstate)
Martin v. Löwis6b449f42007-12-03 19:20:02 +0000128 elif version == 2:
129 version, internalstate, self.gauss_next = state
130 # In version 2, the state was saved as signed ints, which causes
131 # inconsistencies between 32/64-bit systems. The state is
132 # really unsigned 32-bit ints, so we convert negative ints from
133 # version 2 to positive longs for version 3.
134 try:
135 internalstate = tuple( long(x) % (2**32) for x in internalstate )
136 except ValueError, e:
137 raise TypeError, e
138 super(Random, self).setstate(internalstate)
Tim Peterscd804102001-01-25 20:25:57 +0000139 else:
140 raise ValueError("state with version %s passed to "
141 "Random.setstate() of version %s" %
142 (version, self.VERSION))
143
Tim Peterscd804102001-01-25 20:25:57 +0000144## ---- Methods below this point do not need to be overridden when
145## ---- subclassing for the purpose of using a different core generator.
146
147## -------------------- pickle support -------------------
148
149 def __getstate__(self): # for pickle
150 return self.getstate()
151
152 def __setstate__(self, state): # for pickle
153 self.setstate(state)
154
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000155 def __reduce__(self):
156 return self.__class__, (), self.getstate()
157
Tim Peterscd804102001-01-25 20:25:57 +0000158## -------------------- integer methods -------------------
159
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000160 def randrange(self, start, stop=None, step=1, int=int, default=None,
161 maxwidth=1L<<BPF):
Tim Petersd7b5e882001-01-25 03:36:26 +0000162 """Choose a random item from range(start, stop[, step]).
163
164 This fixes the problem with randint() which includes the
165 endpoint; in Python this is usually not what you want.
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000166 Do not supply the 'int', 'default', and 'maxwidth' arguments.
Tim Petersd7b5e882001-01-25 03:36:26 +0000167 """
168
169 # This code is a bit messy to make it fast for the
Tim Peters9146f272002-08-16 03:41:39 +0000170 # common case while still doing adequate error checking.
Tim Petersd7b5e882001-01-25 03:36:26 +0000171 istart = int(start)
172 if istart != start:
173 raise ValueError, "non-integer arg 1 for randrange()"
174 if stop is default:
175 if istart > 0:
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000176 if istart >= maxwidth:
177 return self._randbelow(istart)
Tim Petersd7b5e882001-01-25 03:36:26 +0000178 return int(self.random() * istart)
179 raise ValueError, "empty range for randrange()"
Tim Peters9146f272002-08-16 03:41:39 +0000180
181 # stop argument supplied.
Tim Petersd7b5e882001-01-25 03:36:26 +0000182 istop = int(stop)
183 if istop != stop:
184 raise ValueError, "non-integer stop for randrange()"
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000185 width = istop - istart
186 if step == 1 and width > 0:
Tim Peters76ca1d42003-06-19 03:46:46 +0000187 # Note that
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000188 # int(istart + self.random()*width)
Tim Peters76ca1d42003-06-19 03:46:46 +0000189 # instead would be incorrect. For example, consider istart
190 # = -2 and istop = 0. Then the guts would be in
191 # -2.0 to 0.0 exclusive on both ends (ignoring that random()
192 # might return 0.0), and because int() truncates toward 0, the
193 # final result would be -1 or 0 (instead of -2 or -1).
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000194 # istart + int(self.random()*width)
Tim Peters76ca1d42003-06-19 03:46:46 +0000195 # would also be incorrect, for a subtler reason: the RHS
196 # can return a long, and then randrange() would also return
197 # a long, but we're supposed to return an int (for backward
198 # compatibility).
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000199
200 if width >= maxwidth:
Tim Peters58eb11c2004-01-18 20:29:55 +0000201 return int(istart + self._randbelow(width))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000202 return int(istart + int(self.random()*width))
Tim Petersd7b5e882001-01-25 03:36:26 +0000203 if step == 1:
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000204 raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
Tim Peters9146f272002-08-16 03:41:39 +0000205
206 # Non-unit step argument supplied.
Tim Petersd7b5e882001-01-25 03:36:26 +0000207 istep = int(step)
208 if istep != step:
209 raise ValueError, "non-integer step for randrange()"
210 if istep > 0:
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000211 n = (width + istep - 1) // istep
Tim Petersd7b5e882001-01-25 03:36:26 +0000212 elif istep < 0:
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000213 n = (width + istep + 1) // istep
Tim Petersd7b5e882001-01-25 03:36:26 +0000214 else:
215 raise ValueError, "zero step for randrange()"
216
217 if n <= 0:
218 raise ValueError, "empty range for randrange()"
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000219
220 if n >= maxwidth:
Raymond Hettinger94547f72006-12-20 06:42:06 +0000221 return istart + istep*self._randbelow(n)
Tim Petersd7b5e882001-01-25 03:36:26 +0000222 return istart + istep*int(self.random() * n)
223
224 def randint(self, a, b):
Tim Peterscd804102001-01-25 20:25:57 +0000225 """Return random integer in range [a, b], including both end points.
Tim Petersd7b5e882001-01-25 03:36:26 +0000226 """
227
228 return self.randrange(a, b+1)
229
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000230 def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L<<BPF,
231 _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
232 """Return a random int in the range [0,n)
233
234 Handles the case where n has more bits than returned
235 by a single call to the underlying generator.
236 """
237
238 try:
239 getrandbits = self.getrandbits
240 except AttributeError:
241 pass
242 else:
243 # Only call self.getrandbits if the original random() builtin method
244 # has not been overridden or if a new getrandbits() was supplied.
245 # This assures that the two methods correspond.
246 if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
247 k = int(1.00001 + _log(n-1, 2.0)) # 2**k > n-1 > 2**(k-2)
248 r = getrandbits(k)
249 while r >= n:
250 r = getrandbits(k)
251 return r
252 if n >= _maxwidth:
253 _warn("Underlying random() generator does not supply \n"
254 "enough bits to choose from a population range this large")
255 return int(self.random() * n)
256
Tim Peterscd804102001-01-25 20:25:57 +0000257## -------------------- sequence methods -------------------
258
Tim Petersd7b5e882001-01-25 03:36:26 +0000259 def choice(self, seq):
260 """Choose a random element from a non-empty sequence."""
Raymond Hettinger5dae5052004-06-07 02:07:15 +0000261 return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
Tim Petersd7b5e882001-01-25 03:36:26 +0000262
263 def shuffle(self, x, random=None, int=int):
264 """x, random=random.random -> shuffle list x in place; return None.
265
266 Optional arg random is a 0-argument function returning a random
267 float in [0.0, 1.0); by default, the standard random.random.
Tim Petersd7b5e882001-01-25 03:36:26 +0000268 """
269
270 if random is None:
271 random = self.random
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000272 for i in reversed(xrange(1, len(x))):
Tim Peterscd804102001-01-25 20:25:57 +0000273 # pick an element in x[:i+1] with which to exchange x[i]
Tim Petersd7b5e882001-01-25 03:36:26 +0000274 j = int(random() * (i+1))
275 x[i], x[j] = x[j], x[i]
276
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000277 def sample(self, population, k):
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000278 """Chooses k unique random elements from a population sequence.
279
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000280 Returns a new list containing elements from the population while
281 leaving the original population unchanged. The resulting list is
282 in selection order so that all sub-slices will also be valid random
283 samples. This allows raffle winners (the sample) to be partitioned
284 into grand prize and second place winners (the subslices).
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000285
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000286 Members of the population need not be hashable or unique. If the
287 population contains repeats, then each occurrence is a possible
288 selection in the sample.
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000289
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000290 To choose a sample in a range of integers, use xrange as an argument.
291 This is especially fast and space efficient for sampling from a
292 large population: sample(xrange(10000000), 60)
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000293 """
294
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000295 # Sampling without replacement entails tracking either potential
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000296 # selections (the pool) in a list or previous selections in a set.
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000297
Jeremy Hylton2b55d352004-02-23 17:27:57 +0000298 # When the number of selections is small compared to the
299 # population, then tracking selections is efficient, requiring
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000300 # only a small set and an occasional reselection. For
Jeremy Hylton2b55d352004-02-23 17:27:57 +0000301 # a larger number of selections, the pool tracking method is
302 # preferred since the list takes less space than the
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000303 # set and it doesn't suffer from frequent reselections.
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000304
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000305 n = len(population)
306 if not 0 <= k <= n:
307 raise ValueError, "sample larger than population"
Raymond Hettinger8b9aa8d2003-01-04 05:20:33 +0000308 random = self.random
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000309 _int = int
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000310 result = [None] * k
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000311 setsize = 21 # size of a small set minus size of an empty list
312 if k > 5:
Tim Peters9e34c042005-08-26 15:20:46 +0000313 setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
Tim Petersc17976e2006-04-01 00:26:53 +0000314 if n <= setsize or hasattr(population, "keys"):
315 # An n-length list is smaller than a k-length set, or this is a
316 # mapping type so the other algorithm wouldn't work.
Raymond Hettinger311f4192002-11-18 09:01:24 +0000317 pool = list(population)
318 for i in xrange(k): # invariant: non-selected at [0,n-i)
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000319 j = _int(random() * (n-i))
Raymond Hettinger311f4192002-11-18 09:01:24 +0000320 result[i] = pool[j]
Raymond Hettinger8b9aa8d2003-01-04 05:20:33 +0000321 pool[j] = pool[n-i-1] # move non-selected item into vacancy
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000322 else:
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000323 try:
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000324 selected = set()
325 selected_add = selected.add
326 for i in xrange(k):
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000327 j = _int(random() * n)
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000328 while j in selected:
329 j = _int(random() * n)
330 selected_add(j)
331 result[i] = population[j]
Tim Petersc17976e2006-04-01 00:26:53 +0000332 except (TypeError, KeyError): # handle (at least) sets
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000333 if isinstance(population, list):
334 raise
Tim Petersc17976e2006-04-01 00:26:53 +0000335 return self.sample(tuple(population), k)
Raymond Hettinger311f4192002-11-18 09:01:24 +0000336 return result
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000337
Tim Peterscd804102001-01-25 20:25:57 +0000338## -------------------- real-valued distributions -------------------
339
340## -------------------- uniform distribution -------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000341
342 def uniform(self, a, b):
Raymond Hettinger2c0cdca2009-06-11 23:14:53 +0000343 "Get a random number in the range [a, b) or [a, b] depending on rounding."
Tim Petersd7b5e882001-01-25 03:36:26 +0000344 return a + (b-a) * self.random()
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000345
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000346## -------------------- triangular --------------------
347
Raymond Hettingerc4f7bab2008-03-23 19:37:53 +0000348 def triangular(self, low=0.0, high=1.0, mode=None):
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000349 """Triangular distribution.
350
351 Continuous distribution bounded by given lower and upper limits,
352 and having a given mode value in-between.
353
354 http://en.wikipedia.org/wiki/Triangular_distribution
355
356 """
357 u = self.random()
Raymond Hettingerc4f7bab2008-03-23 19:37:53 +0000358 c = 0.5 if mode is None else (mode - low) / (high - low)
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000359 if u > c:
Raymond Hettingerc4f7bab2008-03-23 19:37:53 +0000360 u = 1.0 - u
361 c = 1.0 - c
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000362 low, high = high, low
363 return low + (high - low) * (u * c) ** 0.5
364
Tim Peterscd804102001-01-25 20:25:57 +0000365## -------------------- normal distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000366
Tim Petersd7b5e882001-01-25 03:36:26 +0000367 def normalvariate(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000368 """Normal distribution.
369
370 mu is the mean, and sigma is the standard deviation.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000371
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000372 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000373 # mu = mean, sigma = standard deviation
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000374
Tim Petersd7b5e882001-01-25 03:36:26 +0000375 # Uses Kinderman and Monahan method. Reference: Kinderman,
376 # A.J. and Monahan, J.F., "Computer generation of random
377 # variables using the ratio of uniform deviates", ACM Trans
378 # Math Software, 3, (1977), pp257-260.
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000379
Tim Petersd7b5e882001-01-25 03:36:26 +0000380 random = self.random
Raymond Hettinger42406e62005-04-30 09:02:51 +0000381 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000382 u1 = random()
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000383 u2 = 1.0 - random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000384 z = NV_MAGICCONST*(u1-0.5)/u2
385 zz = z*z/4.0
386 if zz <= -_log(u2):
387 break
388 return mu + z*sigma
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000389
Tim Peterscd804102001-01-25 20:25:57 +0000390## -------------------- lognormal distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000391
392 def lognormvariate(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000393 """Log normal distribution.
394
395 If you take the natural logarithm of this distribution, you'll get a
396 normal distribution with mean mu and standard deviation sigma.
397 mu can have any value, and sigma must be greater than zero.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000398
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000399 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000400 return _exp(self.normalvariate(mu, sigma))
401
Tim Peterscd804102001-01-25 20:25:57 +0000402## -------------------- exponential distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000403
404 def expovariate(self, lambd):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000405 """Exponential distribution.
406
Mark Dickinsone6dc5312009-01-07 17:48:33 +0000407 lambd is 1.0 divided by the desired mean. It should be
408 nonzero. (The parameter would be called "lambda", but that is
409 a reserved word in Python.) Returned values range from 0 to
410 positive infinity if lambd is positive, and from negative
411 infinity to 0 if lambd is negative.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000412
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000413 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000414 # lambd: rate lambd = 1/mean
415 # ('lambda' is a Python reserved word)
416
417 random = self.random
Tim Peters0c9886d2001-01-15 01:18:21 +0000418 u = random()
419 while u <= 1e-7:
420 u = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000421 return -_log(u)/lambd
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000422
Tim Peterscd804102001-01-25 20:25:57 +0000423## -------------------- von Mises distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000424
Tim Petersd7b5e882001-01-25 03:36:26 +0000425 def vonmisesvariate(self, mu, kappa):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000426 """Circular data distribution.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000427
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000428 mu is the mean angle, expressed in radians between 0 and 2*pi, and
429 kappa is the concentration parameter, which must be greater than or
430 equal to zero. If kappa is equal to zero, this distribution reduces
431 to a uniform random angle over the range 0 to 2*pi.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000432
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000433 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000434 # mu: mean angle (in radians between 0 and 2*pi)
435 # kappa: concentration parameter kappa (>= 0)
436 # if kappa = 0 generate uniform random angle
437
438 # Based upon an algorithm published in: Fisher, N.I.,
439 # "Statistical Analysis of Circular Data", Cambridge
440 # University Press, 1993.
441
442 # Thanks to Magnus Kessler for a correction to the
443 # implementation of step 4.
444
445 random = self.random
446 if kappa <= 1e-6:
447 return TWOPI * random()
448
449 a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)
450 b = (a - _sqrt(2.0 * a))/(2.0 * kappa)
451 r = (1.0 + b * b)/(2.0 * b)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000452
Raymond Hettinger42406e62005-04-30 09:02:51 +0000453 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000454 u1 = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000455
456 z = _cos(_pi * u1)
457 f = (1.0 + r * z)/(r + z)
458 c = kappa * (r - f)
459
460 u2 = random()
461
Raymond Hettinger42406e62005-04-30 09:02:51 +0000462 if u2 < c * (2.0 - c) or u2 <= c * _exp(1.0 - c):
Tim Peters0c9886d2001-01-15 01:18:21 +0000463 break
Tim Petersd7b5e882001-01-25 03:36:26 +0000464
465 u3 = random()
466 if u3 > 0.5:
467 theta = (mu % TWOPI) + _acos(f)
468 else:
469 theta = (mu % TWOPI) - _acos(f)
470
471 return theta
472
Tim Peterscd804102001-01-25 20:25:57 +0000473## -------------------- gamma distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000474
475 def gammavariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000476 """Gamma distribution. Not the gamma function!
477
478 Conditions on the parameters are alpha > 0 and beta > 0.
479
480 """
Tim Peters8ac14952002-05-23 15:15:30 +0000481
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000482 # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
Tim Peters8ac14952002-05-23 15:15:30 +0000483
Guido van Rossum570764d2002-05-14 14:08:12 +0000484 # Warning: a few older sources define the gamma distribution in terms
485 # of alpha > -1.0
486 if alpha <= 0.0 or beta <= 0.0:
487 raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
Tim Peters8ac14952002-05-23 15:15:30 +0000488
Tim Petersd7b5e882001-01-25 03:36:26 +0000489 random = self.random
Tim Petersd7b5e882001-01-25 03:36:26 +0000490 if alpha > 1.0:
491
492 # Uses R.C.H. Cheng, "The generation of Gamma
493 # variables with non-integral shape parameters",
494 # Applied Statistics, (1977), 26, No. 1, p71-74
495
Raymond Hettingerca6cdc22002-05-13 23:40:14 +0000496 ainv = _sqrt(2.0 * alpha - 1.0)
497 bbb = alpha - LOG4
498 ccc = alpha + ainv
Tim Peters8ac14952002-05-23 15:15:30 +0000499
Raymond Hettinger42406e62005-04-30 09:02:51 +0000500 while 1:
Tim Petersd7b5e882001-01-25 03:36:26 +0000501 u1 = random()
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000502 if not 1e-7 < u1 < .9999999:
503 continue
504 u2 = 1.0 - random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000505 v = _log(u1/(1.0-u1))/ainv
506 x = alpha*_exp(v)
507 z = u1*u1*u2
508 r = bbb+ccc*v-x
509 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000510 return x * beta
Tim Petersd7b5e882001-01-25 03:36:26 +0000511
512 elif alpha == 1.0:
513 # expovariate(1)
514 u = random()
515 while u <= 1e-7:
516 u = random()
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000517 return -_log(u) * beta
Tim Petersd7b5e882001-01-25 03:36:26 +0000518
519 else: # alpha is between 0 and 1 (exclusive)
520
521 # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
522
Raymond Hettinger42406e62005-04-30 09:02:51 +0000523 while 1:
Tim Petersd7b5e882001-01-25 03:36:26 +0000524 u = random()
525 b = (_e + alpha)/_e
526 p = b*u
527 if p <= 1.0:
Raymond Hettinger42406e62005-04-30 09:02:51 +0000528 x = p ** (1.0/alpha)
Tim Petersd7b5e882001-01-25 03:36:26 +0000529 else:
Tim Petersd7b5e882001-01-25 03:36:26 +0000530 x = -_log((b-p)/alpha)
531 u1 = random()
Raymond Hettinger42406e62005-04-30 09:02:51 +0000532 if p > 1.0:
533 if u1 <= x ** (alpha - 1.0):
534 break
535 elif u1 <= _exp(-x):
Tim Petersd7b5e882001-01-25 03:36:26 +0000536 break
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000537 return x * beta
538
Tim Peterscd804102001-01-25 20:25:57 +0000539## -------------------- Gauss (faster alternative) --------------------
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000540
Tim Petersd7b5e882001-01-25 03:36:26 +0000541 def gauss(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000542 """Gaussian distribution.
543
544 mu is the mean, and sigma is the standard deviation. This is
545 slightly faster than the normalvariate() function.
546
547 Not thread-safe without a lock around calls.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000548
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000549 """
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000550
Tim Petersd7b5e882001-01-25 03:36:26 +0000551 # When x and y are two variables from [0, 1), uniformly
552 # distributed, then
553 #
554 # cos(2*pi*x)*sqrt(-2*log(1-y))
555 # sin(2*pi*x)*sqrt(-2*log(1-y))
556 #
557 # are two *independent* variables with normal distribution
558 # (mu = 0, sigma = 1).
559 # (Lambert Meertens)
560 # (corrected version; bug discovered by Mike Miller, fixed by LM)
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000561
Tim Petersd7b5e882001-01-25 03:36:26 +0000562 # Multithreading note: When two threads call this function
563 # simultaneously, it is possible that they will receive the
564 # same return value. The window is very small though. To
565 # avoid this, you have to use a lock around all calls. (I
566 # didn't want to slow this down in the serial case by using a
567 # lock here.)
Guido van Rossumd03e1191998-05-29 17:51:31 +0000568
Tim Petersd7b5e882001-01-25 03:36:26 +0000569 random = self.random
570 z = self.gauss_next
571 self.gauss_next = None
572 if z is None:
573 x2pi = random() * TWOPI
574 g2rad = _sqrt(-2.0 * _log(1.0 - random()))
575 z = _cos(x2pi) * g2rad
576 self.gauss_next = _sin(x2pi) * g2rad
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000577
Tim Petersd7b5e882001-01-25 03:36:26 +0000578 return mu + z*sigma
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000579
Tim Peterscd804102001-01-25 20:25:57 +0000580## -------------------- beta --------------------
Tim Peters85e2e472001-01-26 06:49:56 +0000581## See
582## http://sourceforge.net/bugs/?func=detailbug&bug_id=130030&group_id=5470
583## for Ivan Frohne's insightful analysis of why the original implementation:
584##
585## def betavariate(self, alpha, beta):
586## # Discrete Event Simulation in C, pp 87-88.
587##
588## y = self.expovariate(alpha)
589## z = self.expovariate(1.0/beta)
590## return z/(y+z)
591##
592## was dead wrong, and how it probably got that way.
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000593
Tim Petersd7b5e882001-01-25 03:36:26 +0000594 def betavariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000595 """Beta distribution.
596
Raymond Hettinger1b0ce852007-01-19 18:07:18 +0000597 Conditions on the parameters are alpha > 0 and beta > 0.
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000598 Returned values range between 0 and 1.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000599
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000600 """
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000601
Tim Peters85e2e472001-01-26 06:49:56 +0000602 # This version due to Janne Sinkkonen, and matches all the std
603 # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
604 y = self.gammavariate(alpha, 1.)
605 if y == 0:
606 return 0.0
607 else:
608 return y / (y + self.gammavariate(beta, 1.))
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000609
Tim Peterscd804102001-01-25 20:25:57 +0000610## -------------------- Pareto --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000611
Tim Petersd7b5e882001-01-25 03:36:26 +0000612 def paretovariate(self, alpha):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000613 """Pareto distribution. alpha is the shape parameter."""
Tim Petersd7b5e882001-01-25 03:36:26 +0000614 # Jain, pg. 495
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000615
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000616 u = 1.0 - self.random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000617 return 1.0 / pow(u, 1.0/alpha)
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000618
Tim Peterscd804102001-01-25 20:25:57 +0000619## -------------------- Weibull --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000620
Tim Petersd7b5e882001-01-25 03:36:26 +0000621 def weibullvariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000622 """Weibull distribution.
623
624 alpha is the scale parameter and beta is the shape parameter.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000625
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000626 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000627 # Jain, pg. 499; bug fix courtesy Bill Arms
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000628
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000629 u = 1.0 - self.random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000630 return alpha * pow(-_log(u), 1.0/beta)
Guido van Rossum6c395ba1999-08-18 13:53:28 +0000631
Raymond Hettinger40f62172002-12-29 23:03:38 +0000632## -------------------- Wichmann-Hill -------------------
633
634class WichmannHill(Random):
635
636 VERSION = 1 # used by getstate/setstate
637
638 def seed(self, a=None):
639 """Initialize internal state from hashable object.
640
Raymond Hettinger23f12412004-09-13 22:23:21 +0000641 None or no argument seeds from current time or from an operating
642 system specific randomness source if available.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000643
644 If a is not None or an int or long, hash(a) is used instead.
645
646 If a is an int or long, a is used directly. Distinct values between
647 0 and 27814431486575L inclusive are guaranteed to yield distinct
648 internal states (this guarantee is specific to the default
649 Wichmann-Hill generator).
650 """
651
652 if a is None:
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000653 try:
654 a = long(_hexlify(_urandom(16)), 16)
655 except NotImplementedError:
Raymond Hettinger356a4592004-08-30 06:14:31 +0000656 import time
657 a = long(time.time() * 256) # use fractional seconds
Raymond Hettinger40f62172002-12-29 23:03:38 +0000658
659 if not isinstance(a, (int, long)):
660 a = hash(a)
661
662 a, x = divmod(a, 30268)
663 a, y = divmod(a, 30306)
664 a, z = divmod(a, 30322)
665 self._seed = int(x)+1, int(y)+1, int(z)+1
666
667 self.gauss_next = None
668
669 def random(self):
670 """Get the next random number in the range [0.0, 1.0)."""
671
672 # Wichman-Hill random number generator.
673 #
674 # Wichmann, B. A. & Hill, I. D. (1982)
675 # Algorithm AS 183:
676 # An efficient and portable pseudo-random number generator
677 # Applied Statistics 31 (1982) 188-190
678 #
679 # see also:
680 # Correction to Algorithm AS 183
681 # Applied Statistics 33 (1984) 123
682 #
683 # McLeod, A. I. (1985)
684 # A remark on Algorithm AS 183
685 # Applied Statistics 34 (1985),198-200
686
687 # This part is thread-unsafe:
688 # BEGIN CRITICAL SECTION
689 x, y, z = self._seed
690 x = (171 * x) % 30269
691 y = (172 * y) % 30307
692 z = (170 * z) % 30323
693 self._seed = x, y, z
694 # END CRITICAL SECTION
695
696 # Note: on a platform using IEEE-754 double arithmetic, this can
697 # never return 0.0 (asserted by Tim; proof too long for a comment).
698 return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
699
700 def getstate(self):
701 """Return internal state; can be passed to setstate() later."""
702 return self.VERSION, self._seed, self.gauss_next
703
704 def setstate(self, state):
705 """Restore internal state from object returned by getstate()."""
706 version = state[0]
707 if version == 1:
708 version, self._seed, self.gauss_next = state
709 else:
710 raise ValueError("state with version %s passed to "
711 "Random.setstate() of version %s" %
712 (version, self.VERSION))
713
714 def jumpahead(self, n):
715 """Act as if n calls to random() were made, but quickly.
716
717 n is an int, greater than or equal to 0.
718
719 Example use: If you have 2 threads and know that each will
720 consume no more than a million random numbers, create two Random
721 objects r1 and r2, then do
722 r2.setstate(r1.getstate())
723 r2.jumpahead(1000000)
724 Then r1 and r2 will use guaranteed-disjoint segments of the full
725 period.
726 """
727
728 if not n >= 0:
729 raise ValueError("n must be >= 0")
730 x, y, z = self._seed
731 x = int(x * pow(171, n, 30269)) % 30269
732 y = int(y * pow(172, n, 30307)) % 30307
733 z = int(z * pow(170, n, 30323)) % 30323
734 self._seed = x, y, z
735
736 def __whseed(self, x=0, y=0, z=0):
737 """Set the Wichmann-Hill seed from (x, y, z).
738
739 These must be integers in the range [0, 256).
740 """
741
742 if not type(x) == type(y) == type(z) == int:
743 raise TypeError('seeds must be integers')
744 if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256):
745 raise ValueError('seeds must be in range(0, 256)')
746 if 0 == x == y == z:
747 # Initialize from current time
748 import time
749 t = long(time.time() * 256)
750 t = int((t&0xffffff) ^ (t>>24))
751 t, x = divmod(t, 256)
752 t, y = divmod(t, 256)
753 t, z = divmod(t, 256)
754 # Zero is a poor seed, so substitute 1
755 self._seed = (x or 1, y or 1, z or 1)
756
757 self.gauss_next = None
758
759 def whseed(self, a=None):
760 """Seed from hashable object's hash code.
761
762 None or no argument seeds from current time. It is not guaranteed
763 that objects with distinct hash codes lead to distinct internal
764 states.
765
766 This is obsolete, provided for compatibility with the seed routine
767 used prior to Python 2.1. Use the .seed() method instead.
768 """
769
770 if a is None:
771 self.__whseed()
772 return
773 a = hash(a)
774 a, x = divmod(a, 256)
775 a, y = divmod(a, 256)
776 a, z = divmod(a, 256)
777 x = (x + a) % 256 or 1
778 y = (y + a) % 256 or 1
779 z = (z + a) % 256 or 1
780 self.__whseed(x, y, z)
781
Raymond Hettinger23f12412004-09-13 22:23:21 +0000782## --------------- Operating System Random Source ------------------
Raymond Hettinger356a4592004-08-30 06:14:31 +0000783
Raymond Hettinger23f12412004-09-13 22:23:21 +0000784class SystemRandom(Random):
785 """Alternate random number generator using sources provided
786 by the operating system (such as /dev/urandom on Unix or
787 CryptGenRandom on Windows).
Raymond Hettinger356a4592004-08-30 06:14:31 +0000788
789 Not available on all systems (see os.urandom() for details).
790 """
791
792 def random(self):
793 """Get the next random number in the range [0.0, 1.0)."""
Tim Peters7c2a85b2004-08-31 02:19:55 +0000794 return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Raymond Hettinger356a4592004-08-30 06:14:31 +0000795
796 def getrandbits(self, k):
797 """getrandbits(k) -> x. Generates a long int with k random bits."""
Raymond Hettinger356a4592004-08-30 06:14:31 +0000798 if k <= 0:
799 raise ValueError('number of bits must be greater than zero')
800 if k != int(k):
801 raise TypeError('number of bits should be an integer')
802 bytes = (k + 7) // 8 # bits / 8 and rounded up
803 x = long(_hexlify(_urandom(bytes)), 16)
804 return x >> (bytes * 8 - k) # trim excess bits
805
806 def _stub(self, *args, **kwds):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000807 "Stub method. Not used for a system random number generator."
Raymond Hettinger356a4592004-08-30 06:14:31 +0000808 return None
809 seed = jumpahead = _stub
810
811 def _notimplemented(self, *args, **kwds):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000812 "Method should not be called for a system random number generator."
813 raise NotImplementedError('System entropy source does not have state.')
Raymond Hettinger356a4592004-08-30 06:14:31 +0000814 getstate = setstate = _notimplemented
815
Tim Peterscd804102001-01-25 20:25:57 +0000816## -------------------- test program --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000817
Raymond Hettinger62297132003-08-30 01:24:19 +0000818def _test_generator(n, func, args):
Tim Peters0c9886d2001-01-15 01:18:21 +0000819 import time
Raymond Hettinger62297132003-08-30 01:24:19 +0000820 print n, 'times', func.__name__
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000821 total = 0.0
Tim Peters0c9886d2001-01-15 01:18:21 +0000822 sqsum = 0.0
823 smallest = 1e10
824 largest = -1e10
825 t0 = time.time()
826 for i in range(n):
Raymond Hettinger62297132003-08-30 01:24:19 +0000827 x = func(*args)
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000828 total += x
Tim Peters0c9886d2001-01-15 01:18:21 +0000829 sqsum = sqsum + x*x
830 smallest = min(x, smallest)
831 largest = max(x, largest)
832 t1 = time.time()
833 print round(t1-t0, 3), 'sec,',
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000834 avg = total/n
Tim Petersd7b5e882001-01-25 03:36:26 +0000835 stddev = _sqrt(sqsum/n - avg*avg)
Tim Peters0c9886d2001-01-15 01:18:21 +0000836 print 'avg %g, stddev %g, min %g, max %g' % \
837 (avg, stddev, smallest, largest)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000838
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000839
840def _test(N=2000):
Raymond Hettinger62297132003-08-30 01:24:19 +0000841 _test_generator(N, random, ())
842 _test_generator(N, normalvariate, (0.0, 1.0))
843 _test_generator(N, lognormvariate, (0.0, 1.0))
844 _test_generator(N, vonmisesvariate, (0.0, 1.0))
845 _test_generator(N, gammavariate, (0.01, 1.0))
846 _test_generator(N, gammavariate, (0.1, 1.0))
847 _test_generator(N, gammavariate, (0.1, 2.0))
848 _test_generator(N, gammavariate, (0.5, 1.0))
849 _test_generator(N, gammavariate, (0.9, 1.0))
850 _test_generator(N, gammavariate, (1.0, 1.0))
851 _test_generator(N, gammavariate, (2.0, 1.0))
852 _test_generator(N, gammavariate, (20.0, 1.0))
853 _test_generator(N, gammavariate, (200.0, 1.0))
854 _test_generator(N, gauss, (0.0, 1.0))
855 _test_generator(N, betavariate, (3.0, 3.0))
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000856 _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0))
Tim Peterscd804102001-01-25 20:25:57 +0000857
Tim Peters715c4c42001-01-26 22:56:56 +0000858# Create one instance, seeded from current time, and export its methods
Raymond Hettinger40f62172002-12-29 23:03:38 +0000859# as module-level functions. The functions share state across all uses
860#(both in the user's code and in the Python libraries), but that's fine
861# for most programs and is easier for the casual user than making them
862# instantiate their own Random() instance.
863
Tim Petersd7b5e882001-01-25 03:36:26 +0000864_inst = Random()
865seed = _inst.seed
866random = _inst.random
867uniform = _inst.uniform
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000868triangular = _inst.triangular
Tim Petersd7b5e882001-01-25 03:36:26 +0000869randint = _inst.randint
870choice = _inst.choice
871randrange = _inst.randrange
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000872sample = _inst.sample
Tim Petersd7b5e882001-01-25 03:36:26 +0000873shuffle = _inst.shuffle
874normalvariate = _inst.normalvariate
875lognormvariate = _inst.lognormvariate
Tim Petersd7b5e882001-01-25 03:36:26 +0000876expovariate = _inst.expovariate
877vonmisesvariate = _inst.vonmisesvariate
878gammavariate = _inst.gammavariate
Tim Petersd7b5e882001-01-25 03:36:26 +0000879gauss = _inst.gauss
880betavariate = _inst.betavariate
881paretovariate = _inst.paretovariate
882weibullvariate = _inst.weibullvariate
883getstate = _inst.getstate
884setstate = _inst.setstate
Tim Petersd52269b2001-01-25 06:23:18 +0000885jumpahead = _inst.jumpahead
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000886getrandbits = _inst.getrandbits
Tim Petersd7b5e882001-01-25 03:36:26 +0000887
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000888if __name__ == '__main__':
Tim Petersd7b5e882001-01-25 03:36:26 +0000889 _test()