blob: 13125e2af283a098dfbfea759a83f87e3aaf02f9 [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 Hettinger2f726e92003-10-05 09:09:15 +000042from warnings import warn as _warn
43from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType
Raymond Hettinger91e27c22005-08-19 01:36:35 +000044from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
Tim Petersd7b5e882001-01-25 03:36:26 +000045from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +000046from os import urandom as _urandom
47from binascii import hexlify as _hexlify
Guido van Rossumff03b1a1994-03-09 12:55:02 +000048
Raymond Hettingerf24eb352002-11-12 17:41:57 +000049__all__ = ["Random","seed","random","uniform","randint","choice","sample",
Skip Montanaro0de65802001-02-15 22:15:14 +000050 "randrange","shuffle","normalvariate","lognormvariate",
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +000051 "expovariate","vonmisesvariate","gammavariate","triangular",
Raymond Hettingerf8a52d32003-08-05 12:23:19 +000052 "gauss","betavariate","paretovariate","weibullvariate",
Raymond Hettinger356a4592004-08-30 06:14:31 +000053 "getstate","setstate","jumpahead", "WichmannHill", "getrandbits",
Raymond Hettinger23f12412004-09-13 22:23:21 +000054 "SystemRandom"]
Tim Petersd7b5e882001-01-25 03:36:26 +000055
56NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
Tim Petersd7b5e882001-01-25 03:36:26 +000057TWOPI = 2.0*_pi
Tim Petersd7b5e882001-01-25 03:36:26 +000058LOG4 = _log(4.0)
Tim Petersd7b5e882001-01-25 03:36:26 +000059SG_MAGICCONST = 1.0 + _log(4.5)
Raymond Hettinger2f726e92003-10-05 09:09:15 +000060BPF = 53 # Number of bits in a float
Tim Peters7c2a85b2004-08-31 02:19:55 +000061RECIP_BPF = 2**-BPF
Tim Petersd7b5e882001-01-25 03:36:26 +000062
Raymond Hettinger356a4592004-08-30 06:14:31 +000063
Tim Petersd7b5e882001-01-25 03:36:26 +000064# Translated by Guido van Rossum from C source provided by
Raymond Hettinger40f62172002-12-29 23:03:38 +000065# Adrian Baddeley. Adapted by Raymond Hettinger for use with
Raymond Hettinger3fa19d72004-08-31 01:05:15 +000066# the Mersenne Twister and os.urandom() core generators.
Tim Petersd7b5e882001-01-25 03:36:26 +000067
Raymond Hettinger145a4a02003-01-07 10:25:55 +000068import _random
Raymond Hettinger40f62172002-12-29 23:03:38 +000069
Raymond Hettinger145a4a02003-01-07 10:25:55 +000070class Random(_random.Random):
Raymond Hettingerc32f0332002-05-23 19:44:49 +000071 """Random number generator base class used by bound module functions.
72
73 Used to instantiate instances of Random to get generators that don't
74 share state. Especially useful for multi-threaded programs, creating
75 a different instance of Random for each thread, and using the jumpahead()
76 method to ensure that the generated sequences seen by each thread don't
77 overlap.
78
79 Class Random can also be subclassed if you want to use a different basic
80 generator of your own devising: in that case, override the following
81 methods: random(), seed(), getstate(), setstate() and jumpahead().
Raymond Hettinger2f726e92003-10-05 09:09:15 +000082 Optionally, implement a getrandombits() method so that randrange()
83 can cover arbitrarily large ranges.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +000084
Raymond Hettingerc32f0332002-05-23 19:44:49 +000085 """
Tim Petersd7b5e882001-01-25 03:36:26 +000086
Martin v. Löwis6b449f42007-12-03 19:20:02 +000087 VERSION = 3 # used by getstate/setstate
Tim Petersd7b5e882001-01-25 03:36:26 +000088
89 def __init__(self, x=None):
90 """Initialize an instance.
91
92 Optional argument x controls seeding, as for Random.seed().
93 """
94
95 self.seed(x)
Raymond Hettinger40f62172002-12-29 23:03:38 +000096 self.gauss_next = None
Tim Petersd7b5e882001-01-25 03:36:26 +000097
Tim Peters0de88fc2001-02-01 04:59:18 +000098 def seed(self, a=None):
99 """Initialize internal state from hashable object.
Tim Petersd7b5e882001-01-25 03:36:26 +0000100
Raymond Hettinger23f12412004-09-13 22:23:21 +0000101 None or no argument seeds from current time or from an operating
102 system specific randomness source if available.
Tim Peters0de88fc2001-02-01 04:59:18 +0000103
Tim Petersbcd725f2001-02-01 10:06:53 +0000104 If a is not None or an int or long, hash(a) is used instead.
Tim Petersd7b5e882001-01-25 03:36:26 +0000105 """
106
Raymond Hettinger3081d592003-08-09 18:30:57 +0000107 if a is None:
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000108 try:
109 a = long(_hexlify(_urandom(16)), 16)
110 except NotImplementedError:
Raymond Hettinger356a4592004-08-30 06:14:31 +0000111 import time
112 a = long(time.time() * 256) # use fractional seconds
Raymond Hettinger356a4592004-08-30 06:14:31 +0000113
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000114 super(Random, self).seed(a)
Tim Peters46c04e12002-05-05 20:40:00 +0000115 self.gauss_next = None
116
Tim Peterscd804102001-01-25 20:25:57 +0000117 def getstate(self):
118 """Return internal state; can be passed to setstate() later."""
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000119 return self.VERSION, super(Random, self).getstate(), self.gauss_next
Tim Peterscd804102001-01-25 20:25:57 +0000120
121 def setstate(self, state):
122 """Restore internal state from object returned by getstate()."""
123 version = state[0]
Martin v. Löwis6b449f42007-12-03 19:20:02 +0000124 if version == 3:
Raymond Hettinger40f62172002-12-29 23:03:38 +0000125 version, internalstate, self.gauss_next = state
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000126 super(Random, self).setstate(internalstate)
Martin v. Löwis6b449f42007-12-03 19:20:02 +0000127 elif version == 2:
128 version, internalstate, self.gauss_next = state
129 # In version 2, the state was saved as signed ints, which causes
130 # inconsistencies between 32/64-bit systems. The state is
131 # really unsigned 32-bit ints, so we convert negative ints from
132 # version 2 to positive longs for version 3.
133 try:
134 internalstate = tuple( long(x) % (2**32) for x in internalstate )
135 except ValueError, e:
136 raise TypeError, e
137 super(Random, self).setstate(internalstate)
Tim Peterscd804102001-01-25 20:25:57 +0000138 else:
139 raise ValueError("state with version %s passed to "
140 "Random.setstate() of version %s" %
141 (version, self.VERSION))
142
Tim Peterscd804102001-01-25 20:25:57 +0000143## ---- Methods below this point do not need to be overridden when
144## ---- subclassing for the purpose of using a different core generator.
145
146## -------------------- pickle support -------------------
147
148 def __getstate__(self): # for pickle
149 return self.getstate()
150
151 def __setstate__(self, state): # for pickle
152 self.setstate(state)
153
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000154 def __reduce__(self):
155 return self.__class__, (), self.getstate()
156
Tim Peterscd804102001-01-25 20:25:57 +0000157## -------------------- integer methods -------------------
158
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000159 def randrange(self, start, stop=None, step=1, int=int, default=None,
160 maxwidth=1L<<BPF):
Tim Petersd7b5e882001-01-25 03:36:26 +0000161 """Choose a random item from range(start, stop[, step]).
162
163 This fixes the problem with randint() which includes the
164 endpoint; in Python this is usually not what you want.
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000165 Do not supply the 'int', 'default', and 'maxwidth' arguments.
Tim Petersd7b5e882001-01-25 03:36:26 +0000166 """
167
168 # This code is a bit messy to make it fast for the
Tim Peters9146f272002-08-16 03:41:39 +0000169 # common case while still doing adequate error checking.
Tim Petersd7b5e882001-01-25 03:36:26 +0000170 istart = int(start)
171 if istart != start:
172 raise ValueError, "non-integer arg 1 for randrange()"
173 if stop is default:
174 if istart > 0:
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000175 if istart >= maxwidth:
176 return self._randbelow(istart)
Tim Petersd7b5e882001-01-25 03:36:26 +0000177 return int(self.random() * istart)
178 raise ValueError, "empty range for randrange()"
Tim Peters9146f272002-08-16 03:41:39 +0000179
180 # stop argument supplied.
Tim Petersd7b5e882001-01-25 03:36:26 +0000181 istop = int(stop)
182 if istop != stop:
183 raise ValueError, "non-integer stop for randrange()"
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000184 width = istop - istart
185 if step == 1 and width > 0:
Tim Peters76ca1d42003-06-19 03:46:46 +0000186 # Note that
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000187 # int(istart + self.random()*width)
Tim Peters76ca1d42003-06-19 03:46:46 +0000188 # instead would be incorrect. For example, consider istart
189 # = -2 and istop = 0. Then the guts would be in
190 # -2.0 to 0.0 exclusive on both ends (ignoring that random()
191 # might return 0.0), and because int() truncates toward 0, the
192 # final result would be -1 or 0 (instead of -2 or -1).
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000193 # istart + int(self.random()*width)
Tim Peters76ca1d42003-06-19 03:46:46 +0000194 # would also be incorrect, for a subtler reason: the RHS
195 # can return a long, and then randrange() would also return
196 # a long, but we're supposed to return an int (for backward
197 # compatibility).
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000198
199 if width >= maxwidth:
Tim Peters58eb11c2004-01-18 20:29:55 +0000200 return int(istart + self._randbelow(width))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000201 return int(istart + int(self.random()*width))
Tim Petersd7b5e882001-01-25 03:36:26 +0000202 if step == 1:
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000203 raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
Tim Peters9146f272002-08-16 03:41:39 +0000204
205 # Non-unit step argument supplied.
Tim Petersd7b5e882001-01-25 03:36:26 +0000206 istep = int(step)
207 if istep != step:
208 raise ValueError, "non-integer step for randrange()"
209 if istep > 0:
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000210 n = (width + istep - 1) // istep
Tim Petersd7b5e882001-01-25 03:36:26 +0000211 elif istep < 0:
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000212 n = (width + istep + 1) // istep
Tim Petersd7b5e882001-01-25 03:36:26 +0000213 else:
214 raise ValueError, "zero step for randrange()"
215
216 if n <= 0:
217 raise ValueError, "empty range for randrange()"
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000218
219 if n >= maxwidth:
Raymond Hettinger94547f72006-12-20 06:42:06 +0000220 return istart + istep*self._randbelow(n)
Tim Petersd7b5e882001-01-25 03:36:26 +0000221 return istart + istep*int(self.random() * n)
222
223 def randint(self, a, b):
Tim Peterscd804102001-01-25 20:25:57 +0000224 """Return random integer in range [a, b], including both end points.
Tim Petersd7b5e882001-01-25 03:36:26 +0000225 """
226
227 return self.randrange(a, b+1)
228
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000229 def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L<<BPF,
230 _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
231 """Return a random int in the range [0,n)
232
233 Handles the case where n has more bits than returned
234 by a single call to the underlying generator.
235 """
236
237 try:
238 getrandbits = self.getrandbits
239 except AttributeError:
240 pass
241 else:
242 # Only call self.getrandbits if the original random() builtin method
243 # has not been overridden or if a new getrandbits() was supplied.
244 # This assures that the two methods correspond.
245 if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
246 k = int(1.00001 + _log(n-1, 2.0)) # 2**k > n-1 > 2**(k-2)
247 r = getrandbits(k)
248 while r >= n:
249 r = getrandbits(k)
250 return r
251 if n >= _maxwidth:
252 _warn("Underlying random() generator does not supply \n"
253 "enough bits to choose from a population range this large")
254 return int(self.random() * n)
255
Tim Peterscd804102001-01-25 20:25:57 +0000256## -------------------- sequence methods -------------------
257
Tim Petersd7b5e882001-01-25 03:36:26 +0000258 def choice(self, seq):
259 """Choose a random element from a non-empty sequence."""
Raymond Hettinger5dae5052004-06-07 02:07:15 +0000260 return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
Tim Petersd7b5e882001-01-25 03:36:26 +0000261
262 def shuffle(self, x, random=None, int=int):
263 """x, random=random.random -> shuffle list x in place; return None.
264
265 Optional arg random is a 0-argument function returning a random
266 float in [0.0, 1.0); by default, the standard random.random.
Tim Petersd7b5e882001-01-25 03:36:26 +0000267 """
268
269 if random is None:
270 random = self.random
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000271 for i in reversed(xrange(1, len(x))):
Tim Peterscd804102001-01-25 20:25:57 +0000272 # pick an element in x[:i+1] with which to exchange x[i]
Tim Petersd7b5e882001-01-25 03:36:26 +0000273 j = int(random() * (i+1))
274 x[i], x[j] = x[j], x[i]
275
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000276 def sample(self, population, k):
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000277 """Chooses k unique random elements from a population sequence.
278
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000279 Returns a new list containing elements from the population while
280 leaving the original population unchanged. The resulting list is
281 in selection order so that all sub-slices will also be valid random
282 samples. This allows raffle winners (the sample) to be partitioned
283 into grand prize and second place winners (the subslices).
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000284
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000285 Members of the population need not be hashable or unique. If the
286 population contains repeats, then each occurrence is a possible
287 selection in the sample.
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000288
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000289 To choose a sample in a range of integers, use xrange as an argument.
290 This is especially fast and space efficient for sampling from a
291 large population: sample(xrange(10000000), 60)
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000292 """
293
Tim Petersc17976e2006-04-01 00:26:53 +0000294 # XXX Although the documentation says `population` is "a sequence",
295 # XXX attempts are made to cater to any iterable with a __len__
296 # XXX method. This has had mixed success. Examples from both
297 # XXX sides: sets work fine, and should become officially supported;
298 # XXX dicts are much harder, and have failed in various subtle
299 # XXX ways across attempts. Support for mapping types should probably
300 # XXX be dropped (and users should pass mapping.keys() or .values()
301 # XXX explicitly).
302
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000303 # Sampling without replacement entails tracking either potential
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000304 # selections (the pool) in a list or previous selections in a set.
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000305
Jeremy Hylton2b55d352004-02-23 17:27:57 +0000306 # When the number of selections is small compared to the
307 # population, then tracking selections is efficient, requiring
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000308 # only a small set and an occasional reselection. For
Jeremy Hylton2b55d352004-02-23 17:27:57 +0000309 # a larger number of selections, the pool tracking method is
310 # preferred since the list takes less space than the
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000311 # set and it doesn't suffer from frequent reselections.
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000312
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000313 n = len(population)
314 if not 0 <= k <= n:
315 raise ValueError, "sample larger than population"
Raymond Hettinger8b9aa8d2003-01-04 05:20:33 +0000316 random = self.random
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000317 _int = int
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000318 result = [None] * k
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000319 setsize = 21 # size of a small set minus size of an empty list
320 if k > 5:
Tim Peters9e34c042005-08-26 15:20:46 +0000321 setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
Tim Petersc17976e2006-04-01 00:26:53 +0000322 if n <= setsize or hasattr(population, "keys"):
323 # An n-length list is smaller than a k-length set, or this is a
324 # mapping type so the other algorithm wouldn't work.
Raymond Hettinger311f4192002-11-18 09:01:24 +0000325 pool = list(population)
326 for i in xrange(k): # invariant: non-selected at [0,n-i)
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000327 j = _int(random() * (n-i))
Raymond Hettinger311f4192002-11-18 09:01:24 +0000328 result[i] = pool[j]
Raymond Hettinger8b9aa8d2003-01-04 05:20:33 +0000329 pool[j] = pool[n-i-1] # move non-selected item into vacancy
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000330 else:
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000331 try:
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000332 selected = set()
333 selected_add = selected.add
334 for i in xrange(k):
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000335 j = _int(random() * n)
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000336 while j in selected:
337 j = _int(random() * n)
338 selected_add(j)
339 result[i] = population[j]
Tim Petersc17976e2006-04-01 00:26:53 +0000340 except (TypeError, KeyError): # handle (at least) sets
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000341 if isinstance(population, list):
342 raise
Tim Petersc17976e2006-04-01 00:26:53 +0000343 return self.sample(tuple(population), k)
Raymond Hettinger311f4192002-11-18 09:01:24 +0000344 return result
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000345
Tim Peterscd804102001-01-25 20:25:57 +0000346## -------------------- real-valued distributions -------------------
347
348## -------------------- uniform distribution -------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000349
350 def uniform(self, a, b):
351 """Get a random number in the range [a, b)."""
352 return a + (b-a) * self.random()
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000353
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000354## -------------------- triangular --------------------
355
356 def triangular(self, low, high, mode):
357 """Triangular distribution.
358
359 Continuous distribution bounded by given lower and upper limits,
360 and having a given mode value in-between.
361
362 http://en.wikipedia.org/wiki/Triangular_distribution
363
364 """
365 u = self.random()
366 c = (mode - low) / (high - low)
367 if u > c:
368 u = 1 - u
369 c = 1 - c
370 low, high = high, low
371 return low + (high - low) * (u * c) ** 0.5
372
Tim Peterscd804102001-01-25 20:25:57 +0000373## -------------------- normal distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000374
Tim Petersd7b5e882001-01-25 03:36:26 +0000375 def normalvariate(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000376 """Normal distribution.
377
378 mu is the mean, and sigma is the standard deviation.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000379
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000380 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000381 # mu = mean, sigma = standard deviation
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000382
Tim Petersd7b5e882001-01-25 03:36:26 +0000383 # Uses Kinderman and Monahan method. Reference: Kinderman,
384 # A.J. and Monahan, J.F., "Computer generation of random
385 # variables using the ratio of uniform deviates", ACM Trans
386 # Math Software, 3, (1977), pp257-260.
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000387
Tim Petersd7b5e882001-01-25 03:36:26 +0000388 random = self.random
Raymond Hettinger42406e62005-04-30 09:02:51 +0000389 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000390 u1 = random()
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000391 u2 = 1.0 - random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000392 z = NV_MAGICCONST*(u1-0.5)/u2
393 zz = z*z/4.0
394 if zz <= -_log(u2):
395 break
396 return mu + z*sigma
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000397
Tim Peterscd804102001-01-25 20:25:57 +0000398## -------------------- lognormal distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000399
400 def lognormvariate(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000401 """Log normal distribution.
402
403 If you take the natural logarithm of this distribution, you'll get a
404 normal distribution with mean mu and standard deviation sigma.
405 mu can have any value, and sigma must be greater than zero.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000406
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000407 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000408 return _exp(self.normalvariate(mu, sigma))
409
Tim Peterscd804102001-01-25 20:25:57 +0000410## -------------------- exponential distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000411
412 def expovariate(self, lambd):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000413 """Exponential distribution.
414
415 lambd is 1.0 divided by the desired mean. (The parameter would be
416 called "lambda", but that is a reserved word in Python.) Returned
417 values range from 0 to positive infinity.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000418
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000419 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000420 # lambd: rate lambd = 1/mean
421 # ('lambda' is a Python reserved word)
422
423 random = self.random
Tim Peters0c9886d2001-01-15 01:18:21 +0000424 u = random()
425 while u <= 1e-7:
426 u = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000427 return -_log(u)/lambd
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000428
Tim Peterscd804102001-01-25 20:25:57 +0000429## -------------------- von Mises distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000430
Tim Petersd7b5e882001-01-25 03:36:26 +0000431 def vonmisesvariate(self, mu, kappa):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000432 """Circular data distribution.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000433
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000434 mu is the mean angle, expressed in radians between 0 and 2*pi, and
435 kappa is the concentration parameter, which must be greater than or
436 equal to zero. If kappa is equal to zero, this distribution reduces
437 to a uniform random angle over the range 0 to 2*pi.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000438
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000439 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000440 # mu: mean angle (in radians between 0 and 2*pi)
441 # kappa: concentration parameter kappa (>= 0)
442 # if kappa = 0 generate uniform random angle
443
444 # Based upon an algorithm published in: Fisher, N.I.,
445 # "Statistical Analysis of Circular Data", Cambridge
446 # University Press, 1993.
447
448 # Thanks to Magnus Kessler for a correction to the
449 # implementation of step 4.
450
451 random = self.random
452 if kappa <= 1e-6:
453 return TWOPI * random()
454
455 a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)
456 b = (a - _sqrt(2.0 * a))/(2.0 * kappa)
457 r = (1.0 + b * b)/(2.0 * b)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000458
Raymond Hettinger42406e62005-04-30 09:02:51 +0000459 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000460 u1 = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000461
462 z = _cos(_pi * u1)
463 f = (1.0 + r * z)/(r + z)
464 c = kappa * (r - f)
465
466 u2 = random()
467
Raymond Hettinger42406e62005-04-30 09:02:51 +0000468 if u2 < c * (2.0 - c) or u2 <= c * _exp(1.0 - c):
Tim Peters0c9886d2001-01-15 01:18:21 +0000469 break
Tim Petersd7b5e882001-01-25 03:36:26 +0000470
471 u3 = random()
472 if u3 > 0.5:
473 theta = (mu % TWOPI) + _acos(f)
474 else:
475 theta = (mu % TWOPI) - _acos(f)
476
477 return theta
478
Tim Peterscd804102001-01-25 20:25:57 +0000479## -------------------- gamma distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000480
481 def gammavariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000482 """Gamma distribution. Not the gamma function!
483
484 Conditions on the parameters are alpha > 0 and beta > 0.
485
486 """
Tim Peters8ac14952002-05-23 15:15:30 +0000487
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000488 # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
Tim Peters8ac14952002-05-23 15:15:30 +0000489
Guido van Rossum570764d2002-05-14 14:08:12 +0000490 # Warning: a few older sources define the gamma distribution in terms
491 # of alpha > -1.0
492 if alpha <= 0.0 or beta <= 0.0:
493 raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
Tim Peters8ac14952002-05-23 15:15:30 +0000494
Tim Petersd7b5e882001-01-25 03:36:26 +0000495 random = self.random
Tim Petersd7b5e882001-01-25 03:36:26 +0000496 if alpha > 1.0:
497
498 # Uses R.C.H. Cheng, "The generation of Gamma
499 # variables with non-integral shape parameters",
500 # Applied Statistics, (1977), 26, No. 1, p71-74
501
Raymond Hettingerca6cdc22002-05-13 23:40:14 +0000502 ainv = _sqrt(2.0 * alpha - 1.0)
503 bbb = alpha - LOG4
504 ccc = alpha + ainv
Tim Peters8ac14952002-05-23 15:15:30 +0000505
Raymond Hettinger42406e62005-04-30 09:02:51 +0000506 while 1:
Tim Petersd7b5e882001-01-25 03:36:26 +0000507 u1 = random()
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000508 if not 1e-7 < u1 < .9999999:
509 continue
510 u2 = 1.0 - random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000511 v = _log(u1/(1.0-u1))/ainv
512 x = alpha*_exp(v)
513 z = u1*u1*u2
514 r = bbb+ccc*v-x
515 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000516 return x * beta
Tim Petersd7b5e882001-01-25 03:36:26 +0000517
518 elif alpha == 1.0:
519 # expovariate(1)
520 u = random()
521 while u <= 1e-7:
522 u = random()
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000523 return -_log(u) * beta
Tim Petersd7b5e882001-01-25 03:36:26 +0000524
525 else: # alpha is between 0 and 1 (exclusive)
526
527 # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
528
Raymond Hettinger42406e62005-04-30 09:02:51 +0000529 while 1:
Tim Petersd7b5e882001-01-25 03:36:26 +0000530 u = random()
531 b = (_e + alpha)/_e
532 p = b*u
533 if p <= 1.0:
Raymond Hettinger42406e62005-04-30 09:02:51 +0000534 x = p ** (1.0/alpha)
Tim Petersd7b5e882001-01-25 03:36:26 +0000535 else:
Tim Petersd7b5e882001-01-25 03:36:26 +0000536 x = -_log((b-p)/alpha)
537 u1 = random()
Raymond Hettinger42406e62005-04-30 09:02:51 +0000538 if p > 1.0:
539 if u1 <= x ** (alpha - 1.0):
540 break
541 elif u1 <= _exp(-x):
Tim Petersd7b5e882001-01-25 03:36:26 +0000542 break
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000543 return x * beta
544
Tim Peterscd804102001-01-25 20:25:57 +0000545## -------------------- Gauss (faster alternative) --------------------
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000546
Tim Petersd7b5e882001-01-25 03:36:26 +0000547 def gauss(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000548 """Gaussian distribution.
549
550 mu is the mean, and sigma is the standard deviation. This is
551 slightly faster than the normalvariate() function.
552
553 Not thread-safe without a lock around calls.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000554
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000555 """
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000556
Tim Petersd7b5e882001-01-25 03:36:26 +0000557 # When x and y are two variables from [0, 1), uniformly
558 # distributed, then
559 #
560 # cos(2*pi*x)*sqrt(-2*log(1-y))
561 # sin(2*pi*x)*sqrt(-2*log(1-y))
562 #
563 # are two *independent* variables with normal distribution
564 # (mu = 0, sigma = 1).
565 # (Lambert Meertens)
566 # (corrected version; bug discovered by Mike Miller, fixed by LM)
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000567
Tim Petersd7b5e882001-01-25 03:36:26 +0000568 # Multithreading note: When two threads call this function
569 # simultaneously, it is possible that they will receive the
570 # same return value. The window is very small though. To
571 # avoid this, you have to use a lock around all calls. (I
572 # didn't want to slow this down in the serial case by using a
573 # lock here.)
Guido van Rossumd03e1191998-05-29 17:51:31 +0000574
Tim Petersd7b5e882001-01-25 03:36:26 +0000575 random = self.random
576 z = self.gauss_next
577 self.gauss_next = None
578 if z is None:
579 x2pi = random() * TWOPI
580 g2rad = _sqrt(-2.0 * _log(1.0 - random()))
581 z = _cos(x2pi) * g2rad
582 self.gauss_next = _sin(x2pi) * g2rad
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000583
Tim Petersd7b5e882001-01-25 03:36:26 +0000584 return mu + z*sigma
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000585
Tim Peterscd804102001-01-25 20:25:57 +0000586## -------------------- beta --------------------
Tim Peters85e2e472001-01-26 06:49:56 +0000587## See
588## http://sourceforge.net/bugs/?func=detailbug&bug_id=130030&group_id=5470
589## for Ivan Frohne's insightful analysis of why the original implementation:
590##
591## def betavariate(self, alpha, beta):
592## # Discrete Event Simulation in C, pp 87-88.
593##
594## y = self.expovariate(alpha)
595## z = self.expovariate(1.0/beta)
596## return z/(y+z)
597##
598## was dead wrong, and how it probably got that way.
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000599
Tim Petersd7b5e882001-01-25 03:36:26 +0000600 def betavariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000601 """Beta distribution.
602
Raymond Hettinger1b0ce852007-01-19 18:07:18 +0000603 Conditions on the parameters are alpha > 0 and beta > 0.
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000604 Returned values range between 0 and 1.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000605
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000606 """
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000607
Tim Peters85e2e472001-01-26 06:49:56 +0000608 # This version due to Janne Sinkkonen, and matches all the std
609 # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
610 y = self.gammavariate(alpha, 1.)
611 if y == 0:
612 return 0.0
613 else:
614 return y / (y + self.gammavariate(beta, 1.))
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000615
Tim Peterscd804102001-01-25 20:25:57 +0000616## -------------------- Pareto --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000617
Tim Petersd7b5e882001-01-25 03:36:26 +0000618 def paretovariate(self, alpha):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000619 """Pareto distribution. alpha is the shape parameter."""
Tim Petersd7b5e882001-01-25 03:36:26 +0000620 # Jain, pg. 495
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000621
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000622 u = 1.0 - self.random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000623 return 1.0 / pow(u, 1.0/alpha)
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000624
Tim Peterscd804102001-01-25 20:25:57 +0000625## -------------------- Weibull --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000626
Tim Petersd7b5e882001-01-25 03:36:26 +0000627 def weibullvariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000628 """Weibull distribution.
629
630 alpha is the scale parameter and beta is the shape parameter.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000631
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000632 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000633 # Jain, pg. 499; bug fix courtesy Bill Arms
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000634
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000635 u = 1.0 - self.random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000636 return alpha * pow(-_log(u), 1.0/beta)
Guido van Rossum6c395ba1999-08-18 13:53:28 +0000637
Raymond Hettinger40f62172002-12-29 23:03:38 +0000638## -------------------- Wichmann-Hill -------------------
639
640class WichmannHill(Random):
641
642 VERSION = 1 # used by getstate/setstate
643
644 def seed(self, a=None):
645 """Initialize internal state from hashable object.
646
Raymond Hettinger23f12412004-09-13 22:23:21 +0000647 None or no argument seeds from current time or from an operating
648 system specific randomness source if available.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000649
650 If a is not None or an int or long, hash(a) is used instead.
651
652 If a is an int or long, a is used directly. Distinct values between
653 0 and 27814431486575L inclusive are guaranteed to yield distinct
654 internal states (this guarantee is specific to the default
655 Wichmann-Hill generator).
656 """
657
658 if a is None:
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000659 try:
660 a = long(_hexlify(_urandom(16)), 16)
661 except NotImplementedError:
Raymond Hettinger356a4592004-08-30 06:14:31 +0000662 import time
663 a = long(time.time() * 256) # use fractional seconds
Raymond Hettinger40f62172002-12-29 23:03:38 +0000664
665 if not isinstance(a, (int, long)):
666 a = hash(a)
667
668 a, x = divmod(a, 30268)
669 a, y = divmod(a, 30306)
670 a, z = divmod(a, 30322)
671 self._seed = int(x)+1, int(y)+1, int(z)+1
672
673 self.gauss_next = None
674
675 def random(self):
676 """Get the next random number in the range [0.0, 1.0)."""
677
678 # Wichman-Hill random number generator.
679 #
680 # Wichmann, B. A. & Hill, I. D. (1982)
681 # Algorithm AS 183:
682 # An efficient and portable pseudo-random number generator
683 # Applied Statistics 31 (1982) 188-190
684 #
685 # see also:
686 # Correction to Algorithm AS 183
687 # Applied Statistics 33 (1984) 123
688 #
689 # McLeod, A. I. (1985)
690 # A remark on Algorithm AS 183
691 # Applied Statistics 34 (1985),198-200
692
693 # This part is thread-unsafe:
694 # BEGIN CRITICAL SECTION
695 x, y, z = self._seed
696 x = (171 * x) % 30269
697 y = (172 * y) % 30307
698 z = (170 * z) % 30323
699 self._seed = x, y, z
700 # END CRITICAL SECTION
701
702 # Note: on a platform using IEEE-754 double arithmetic, this can
703 # never return 0.0 (asserted by Tim; proof too long for a comment).
704 return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
705
706 def getstate(self):
707 """Return internal state; can be passed to setstate() later."""
708 return self.VERSION, self._seed, self.gauss_next
709
710 def setstate(self, state):
711 """Restore internal state from object returned by getstate()."""
712 version = state[0]
713 if version == 1:
714 version, self._seed, self.gauss_next = state
715 else:
716 raise ValueError("state with version %s passed to "
717 "Random.setstate() of version %s" %
718 (version, self.VERSION))
719
720 def jumpahead(self, n):
721 """Act as if n calls to random() were made, but quickly.
722
723 n is an int, greater than or equal to 0.
724
725 Example use: If you have 2 threads and know that each will
726 consume no more than a million random numbers, create two Random
727 objects r1 and r2, then do
728 r2.setstate(r1.getstate())
729 r2.jumpahead(1000000)
730 Then r1 and r2 will use guaranteed-disjoint segments of the full
731 period.
732 """
733
734 if not n >= 0:
735 raise ValueError("n must be >= 0")
736 x, y, z = self._seed
737 x = int(x * pow(171, n, 30269)) % 30269
738 y = int(y * pow(172, n, 30307)) % 30307
739 z = int(z * pow(170, n, 30323)) % 30323
740 self._seed = x, y, z
741
742 def __whseed(self, x=0, y=0, z=0):
743 """Set the Wichmann-Hill seed from (x, y, z).
744
745 These must be integers in the range [0, 256).
746 """
747
748 if not type(x) == type(y) == type(z) == int:
749 raise TypeError('seeds must be integers')
750 if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256):
751 raise ValueError('seeds must be in range(0, 256)')
752 if 0 == x == y == z:
753 # Initialize from current time
754 import time
755 t = long(time.time() * 256)
756 t = int((t&0xffffff) ^ (t>>24))
757 t, x = divmod(t, 256)
758 t, y = divmod(t, 256)
759 t, z = divmod(t, 256)
760 # Zero is a poor seed, so substitute 1
761 self._seed = (x or 1, y or 1, z or 1)
762
763 self.gauss_next = None
764
765 def whseed(self, a=None):
766 """Seed from hashable object's hash code.
767
768 None or no argument seeds from current time. It is not guaranteed
769 that objects with distinct hash codes lead to distinct internal
770 states.
771
772 This is obsolete, provided for compatibility with the seed routine
773 used prior to Python 2.1. Use the .seed() method instead.
774 """
775
776 if a is None:
777 self.__whseed()
778 return
779 a = hash(a)
780 a, x = divmod(a, 256)
781 a, y = divmod(a, 256)
782 a, z = divmod(a, 256)
783 x = (x + a) % 256 or 1
784 y = (y + a) % 256 or 1
785 z = (z + a) % 256 or 1
786 self.__whseed(x, y, z)
787
Raymond Hettinger23f12412004-09-13 22:23:21 +0000788## --------------- Operating System Random Source ------------------
Raymond Hettinger356a4592004-08-30 06:14:31 +0000789
Raymond Hettinger23f12412004-09-13 22:23:21 +0000790class SystemRandom(Random):
791 """Alternate random number generator using sources provided
792 by the operating system (such as /dev/urandom on Unix or
793 CryptGenRandom on Windows).
Raymond Hettinger356a4592004-08-30 06:14:31 +0000794
795 Not available on all systems (see os.urandom() for details).
796 """
797
798 def random(self):
799 """Get the next random number in the range [0.0, 1.0)."""
Tim Peters7c2a85b2004-08-31 02:19:55 +0000800 return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Raymond Hettinger356a4592004-08-30 06:14:31 +0000801
802 def getrandbits(self, k):
803 """getrandbits(k) -> x. Generates a long int with k random bits."""
Raymond Hettinger356a4592004-08-30 06:14:31 +0000804 if k <= 0:
805 raise ValueError('number of bits must be greater than zero')
806 if k != int(k):
807 raise TypeError('number of bits should be an integer')
808 bytes = (k + 7) // 8 # bits / 8 and rounded up
809 x = long(_hexlify(_urandom(bytes)), 16)
810 return x >> (bytes * 8 - k) # trim excess bits
811
812 def _stub(self, *args, **kwds):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000813 "Stub method. Not used for a system random number generator."
Raymond Hettinger356a4592004-08-30 06:14:31 +0000814 return None
815 seed = jumpahead = _stub
816
817 def _notimplemented(self, *args, **kwds):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000818 "Method should not be called for a system random number generator."
819 raise NotImplementedError('System entropy source does not have state.')
Raymond Hettinger356a4592004-08-30 06:14:31 +0000820 getstate = setstate = _notimplemented
821
Tim Peterscd804102001-01-25 20:25:57 +0000822## -------------------- test program --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000823
Raymond Hettinger62297132003-08-30 01:24:19 +0000824def _test_generator(n, func, args):
Tim Peters0c9886d2001-01-15 01:18:21 +0000825 import time
Raymond Hettinger62297132003-08-30 01:24:19 +0000826 print n, 'times', func.__name__
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000827 total = 0.0
Tim Peters0c9886d2001-01-15 01:18:21 +0000828 sqsum = 0.0
829 smallest = 1e10
830 largest = -1e10
831 t0 = time.time()
832 for i in range(n):
Raymond Hettinger62297132003-08-30 01:24:19 +0000833 x = func(*args)
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000834 total += x
Tim Peters0c9886d2001-01-15 01:18:21 +0000835 sqsum = sqsum + x*x
836 smallest = min(x, smallest)
837 largest = max(x, largest)
838 t1 = time.time()
839 print round(t1-t0, 3), 'sec,',
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000840 avg = total/n
Tim Petersd7b5e882001-01-25 03:36:26 +0000841 stddev = _sqrt(sqsum/n - avg*avg)
Tim Peters0c9886d2001-01-15 01:18:21 +0000842 print 'avg %g, stddev %g, min %g, max %g' % \
843 (avg, stddev, smallest, largest)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000844
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000845
846def _test(N=2000):
Raymond Hettinger62297132003-08-30 01:24:19 +0000847 _test_generator(N, random, ())
848 _test_generator(N, normalvariate, (0.0, 1.0))
849 _test_generator(N, lognormvariate, (0.0, 1.0))
850 _test_generator(N, vonmisesvariate, (0.0, 1.0))
851 _test_generator(N, gammavariate, (0.01, 1.0))
852 _test_generator(N, gammavariate, (0.1, 1.0))
853 _test_generator(N, gammavariate, (0.1, 2.0))
854 _test_generator(N, gammavariate, (0.5, 1.0))
855 _test_generator(N, gammavariate, (0.9, 1.0))
856 _test_generator(N, gammavariate, (1.0, 1.0))
857 _test_generator(N, gammavariate, (2.0, 1.0))
858 _test_generator(N, gammavariate, (20.0, 1.0))
859 _test_generator(N, gammavariate, (200.0, 1.0))
860 _test_generator(N, gauss, (0.0, 1.0))
861 _test_generator(N, betavariate, (3.0, 3.0))
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000862 _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0))
Tim Peterscd804102001-01-25 20:25:57 +0000863
Tim Peters715c4c42001-01-26 22:56:56 +0000864# Create one instance, seeded from current time, and export its methods
Raymond Hettinger40f62172002-12-29 23:03:38 +0000865# as module-level functions. The functions share state across all uses
866#(both in the user's code and in the Python libraries), but that's fine
867# for most programs and is easier for the casual user than making them
868# instantiate their own Random() instance.
869
Tim Petersd7b5e882001-01-25 03:36:26 +0000870_inst = Random()
871seed = _inst.seed
872random = _inst.random
873uniform = _inst.uniform
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000874triangular = _inst.triangular
Tim Petersd7b5e882001-01-25 03:36:26 +0000875randint = _inst.randint
876choice = _inst.choice
877randrange = _inst.randrange
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000878sample = _inst.sample
Tim Petersd7b5e882001-01-25 03:36:26 +0000879shuffle = _inst.shuffle
880normalvariate = _inst.normalvariate
881lognormvariate = _inst.lognormvariate
Tim Petersd7b5e882001-01-25 03:36:26 +0000882expovariate = _inst.expovariate
883vonmisesvariate = _inst.vonmisesvariate
884gammavariate = _inst.gammavariate
Tim Petersd7b5e882001-01-25 03:36:26 +0000885gauss = _inst.gauss
886betavariate = _inst.betavariate
887paretovariate = _inst.paretovariate
888weibullvariate = _inst.weibullvariate
889getstate = _inst.getstate
890setstate = _inst.setstate
Tim Petersd52269b2001-01-25 06:23:18 +0000891jumpahead = _inst.jumpahead
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000892getrandbits = _inst.getrandbits
Tim Petersd7b5e882001-01-25 03:36:26 +0000893
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000894if __name__ == '__main__':
Tim Petersd7b5e882001-01-25 03:36:26 +0000895 _test()