blob: 6fa1c05088900ce9237231e210d9cff5dccf3204 [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
Raymond Hettingerffd2a422010-09-10 10:47:22 +000049import hashlib as _hashlib
Guido van Rossumff03b1a1994-03-09 12:55:02 +000050
Raymond Hettingerf24eb352002-11-12 17:41:57 +000051__all__ = ["Random","seed","random","uniform","randint","choice","sample",
Skip Montanaro0de65802001-02-15 22:15:14 +000052 "randrange","shuffle","normalvariate","lognormvariate",
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +000053 "expovariate","vonmisesvariate","gammavariate","triangular",
Raymond Hettingerf8a52d32003-08-05 12:23:19 +000054 "gauss","betavariate","paretovariate","weibullvariate",
Raymond Hettinger356a4592004-08-30 06:14:31 +000055 "getstate","setstate","jumpahead", "WichmannHill", "getrandbits",
Raymond Hettinger23f12412004-09-13 22:23:21 +000056 "SystemRandom"]
Tim Petersd7b5e882001-01-25 03:36:26 +000057
58NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
Tim Petersd7b5e882001-01-25 03:36:26 +000059TWOPI = 2.0*_pi
Tim Petersd7b5e882001-01-25 03:36:26 +000060LOG4 = _log(4.0)
Tim Petersd7b5e882001-01-25 03:36:26 +000061SG_MAGICCONST = 1.0 + _log(4.5)
Raymond Hettinger2f726e92003-10-05 09:09:15 +000062BPF = 53 # Number of bits in a float
Tim Peters7c2a85b2004-08-31 02:19:55 +000063RECIP_BPF = 2**-BPF
Tim Petersd7b5e882001-01-25 03:36:26 +000064
Raymond Hettinger356a4592004-08-30 06:14:31 +000065
Tim Petersd7b5e882001-01-25 03:36:26 +000066# Translated by Guido van Rossum from C source provided by
Raymond Hettinger40f62172002-12-29 23:03:38 +000067# Adrian Baddeley. Adapted by Raymond Hettinger for use with
Raymond Hettinger3fa19d72004-08-31 01:05:15 +000068# the Mersenne Twister and os.urandom() core generators.
Tim Petersd7b5e882001-01-25 03:36:26 +000069
Raymond Hettinger145a4a02003-01-07 10:25:55 +000070import _random
Raymond Hettinger40f62172002-12-29 23:03:38 +000071
Raymond Hettinger145a4a02003-01-07 10:25:55 +000072class Random(_random.Random):
Raymond Hettingerc32f0332002-05-23 19:44:49 +000073 """Random number generator base class used by bound module functions.
74
75 Used to instantiate instances of Random to get generators that don't
76 share state. Especially useful for multi-threaded programs, creating
77 a different instance of Random for each thread, and using the jumpahead()
78 method to ensure that the generated sequences seen by each thread don't
79 overlap.
80
81 Class Random can also be subclassed if you want to use a different basic
82 generator of your own devising: in that case, override the following
Benjamin Petersonf2eb2b42008-07-30 13:46:53 +000083 methods: random(), seed(), getstate(), setstate() and jumpahead().
84 Optionally, implement a getrandbits() method so that randrange() can cover
85 arbitrarily large ranges.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +000086
Raymond Hettingerc32f0332002-05-23 19:44:49 +000087 """
Tim Petersd7b5e882001-01-25 03:36:26 +000088
Martin v. Löwis6b449f42007-12-03 19:20:02 +000089 VERSION = 3 # used by getstate/setstate
Tim Petersd7b5e882001-01-25 03:36:26 +000090
91 def __init__(self, x=None):
92 """Initialize an instance.
93
94 Optional argument x controls seeding, as for Random.seed().
95 """
96
97 self.seed(x)
Raymond Hettinger40f62172002-12-29 23:03:38 +000098 self.gauss_next = None
Tim Petersd7b5e882001-01-25 03:36:26 +000099
Tim Peters0de88fc2001-02-01 04:59:18 +0000100 def seed(self, a=None):
101 """Initialize internal state from hashable object.
Tim Petersd7b5e882001-01-25 03:36:26 +0000102
Raymond Hettinger23f12412004-09-13 22:23:21 +0000103 None or no argument seeds from current time or from an operating
104 system specific randomness source if available.
Tim Peters0de88fc2001-02-01 04:59:18 +0000105
Tim Petersbcd725f2001-02-01 10:06:53 +0000106 If a is not None or an int or long, hash(a) is used instead.
Tim Petersd7b5e882001-01-25 03:36:26 +0000107 """
108
Raymond Hettinger3081d592003-08-09 18:30:57 +0000109 if a is None:
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000110 try:
111 a = long(_hexlify(_urandom(16)), 16)
112 except NotImplementedError:
Raymond Hettinger356a4592004-08-30 06:14:31 +0000113 import time
114 a = long(time.time() * 256) # use fractional seconds
Raymond Hettinger356a4592004-08-30 06:14:31 +0000115
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000116 super(Random, self).seed(a)
Tim Peters46c04e12002-05-05 20:40:00 +0000117 self.gauss_next = None
118
Tim Peterscd804102001-01-25 20:25:57 +0000119 def getstate(self):
120 """Return internal state; can be passed to setstate() later."""
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000121 return self.VERSION, super(Random, self).getstate(), self.gauss_next
Tim Peterscd804102001-01-25 20:25:57 +0000122
123 def setstate(self, state):
124 """Restore internal state from object returned by getstate()."""
125 version = state[0]
Martin v. Löwis6b449f42007-12-03 19:20:02 +0000126 if version == 3:
Raymond Hettinger40f62172002-12-29 23:03:38 +0000127 version, internalstate, self.gauss_next = state
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000128 super(Random, self).setstate(internalstate)
Martin v. Löwis6b449f42007-12-03 19:20:02 +0000129 elif version == 2:
130 version, internalstate, self.gauss_next = state
131 # In version 2, the state was saved as signed ints, which causes
132 # inconsistencies between 32/64-bit systems. The state is
133 # really unsigned 32-bit ints, so we convert negative ints from
134 # version 2 to positive longs for version 3.
135 try:
136 internalstate = tuple( long(x) % (2**32) for x in internalstate )
137 except ValueError, e:
138 raise TypeError, e
139 super(Random, self).setstate(internalstate)
Tim Peterscd804102001-01-25 20:25:57 +0000140 else:
141 raise ValueError("state with version %s passed to "
142 "Random.setstate() of version %s" %
143 (version, self.VERSION))
144
Raymond Hettingerffd2a422010-09-10 10:47:22 +0000145 def jumpahead(self, n):
146 """Change the internal state to one that is likely far away
147 from the current state. This method will not be in Py3.x,
148 so it is better to simply reseed.
149 """
150 # The super.jumpahead() method uses shuffling to change state,
151 # so it needs a large and "interesting" n to work with. Here,
152 # we use hashing to create a large n for the shuffle.
153 s = repr(n) + repr(self.getstate())
154 n = int(_hashlib.new('sha512', s).hexdigest(), 16)
155 super(Random, self).jumpahead(n)
156
Tim Peterscd804102001-01-25 20:25:57 +0000157## ---- Methods below this point do not need to be overridden when
158## ---- subclassing for the purpose of using a different core generator.
159
160## -------------------- pickle support -------------------
161
162 def __getstate__(self): # for pickle
163 return self.getstate()
164
165 def __setstate__(self, state): # for pickle
166 self.setstate(state)
167
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000168 def __reduce__(self):
169 return self.__class__, (), self.getstate()
170
Tim Peterscd804102001-01-25 20:25:57 +0000171## -------------------- integer methods -------------------
172
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000173 def randrange(self, start, stop=None, step=1, int=int, default=None,
174 maxwidth=1L<<BPF):
Tim Petersd7b5e882001-01-25 03:36:26 +0000175 """Choose a random item from range(start, stop[, step]).
176
177 This fixes the problem with randint() which includes the
178 endpoint; in Python this is usually not what you want.
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000179 Do not supply the 'int', 'default', and 'maxwidth' arguments.
Tim Petersd7b5e882001-01-25 03:36:26 +0000180 """
181
182 # This code is a bit messy to make it fast for the
Tim Peters9146f272002-08-16 03:41:39 +0000183 # common case while still doing adequate error checking.
Tim Petersd7b5e882001-01-25 03:36:26 +0000184 istart = int(start)
185 if istart != start:
186 raise ValueError, "non-integer arg 1 for randrange()"
187 if stop is default:
188 if istart > 0:
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000189 if istart >= maxwidth:
190 return self._randbelow(istart)
Tim Petersd7b5e882001-01-25 03:36:26 +0000191 return int(self.random() * istart)
192 raise ValueError, "empty range for randrange()"
Tim Peters9146f272002-08-16 03:41:39 +0000193
194 # stop argument supplied.
Tim Petersd7b5e882001-01-25 03:36:26 +0000195 istop = int(stop)
196 if istop != stop:
197 raise ValueError, "non-integer stop for randrange()"
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000198 width = istop - istart
199 if step == 1 and width > 0:
Tim Peters76ca1d42003-06-19 03:46:46 +0000200 # Note that
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000201 # int(istart + self.random()*width)
Tim Peters76ca1d42003-06-19 03:46:46 +0000202 # instead would be incorrect. For example, consider istart
203 # = -2 and istop = 0. Then the guts would be in
204 # -2.0 to 0.0 exclusive on both ends (ignoring that random()
205 # might return 0.0), and because int() truncates toward 0, the
206 # final result would be -1 or 0 (instead of -2 or -1).
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000207 # istart + int(self.random()*width)
Tim Peters76ca1d42003-06-19 03:46:46 +0000208 # would also be incorrect, for a subtler reason: the RHS
209 # can return a long, and then randrange() would also return
210 # a long, but we're supposed to return an int (for backward
211 # compatibility).
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000212
213 if width >= maxwidth:
Tim Peters58eb11c2004-01-18 20:29:55 +0000214 return int(istart + self._randbelow(width))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000215 return int(istart + int(self.random()*width))
Tim Petersd7b5e882001-01-25 03:36:26 +0000216 if step == 1:
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000217 raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
Tim Peters9146f272002-08-16 03:41:39 +0000218
219 # Non-unit step argument supplied.
Tim Petersd7b5e882001-01-25 03:36:26 +0000220 istep = int(step)
221 if istep != step:
222 raise ValueError, "non-integer step for randrange()"
223 if istep > 0:
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000224 n = (width + istep - 1) // istep
Tim Petersd7b5e882001-01-25 03:36:26 +0000225 elif istep < 0:
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000226 n = (width + istep + 1) // istep
Tim Petersd7b5e882001-01-25 03:36:26 +0000227 else:
228 raise ValueError, "zero step for randrange()"
229
230 if n <= 0:
231 raise ValueError, "empty range for randrange()"
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000232
233 if n >= maxwidth:
Raymond Hettinger94547f72006-12-20 06:42:06 +0000234 return istart + istep*self._randbelow(n)
Tim Petersd7b5e882001-01-25 03:36:26 +0000235 return istart + istep*int(self.random() * n)
236
237 def randint(self, a, b):
Tim Peterscd804102001-01-25 20:25:57 +0000238 """Return random integer in range [a, b], including both end points.
Tim Petersd7b5e882001-01-25 03:36:26 +0000239 """
240
241 return self.randrange(a, b+1)
242
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000243 def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L<<BPF,
244 _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
245 """Return a random int in the range [0,n)
246
247 Handles the case where n has more bits than returned
248 by a single call to the underlying generator.
249 """
250
251 try:
252 getrandbits = self.getrandbits
253 except AttributeError:
254 pass
255 else:
256 # Only call self.getrandbits if the original random() builtin method
257 # has not been overridden or if a new getrandbits() was supplied.
258 # This assures that the two methods correspond.
259 if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
260 k = int(1.00001 + _log(n-1, 2.0)) # 2**k > n-1 > 2**(k-2)
261 r = getrandbits(k)
262 while r >= n:
263 r = getrandbits(k)
264 return r
265 if n >= _maxwidth:
266 _warn("Underlying random() generator does not supply \n"
267 "enough bits to choose from a population range this large")
268 return int(self.random() * n)
269
Tim Peterscd804102001-01-25 20:25:57 +0000270## -------------------- sequence methods -------------------
271
Tim Petersd7b5e882001-01-25 03:36:26 +0000272 def choice(self, seq):
273 """Choose a random element from a non-empty sequence."""
Raymond Hettinger5dae5052004-06-07 02:07:15 +0000274 return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
Tim Petersd7b5e882001-01-25 03:36:26 +0000275
276 def shuffle(self, x, random=None, int=int):
277 """x, random=random.random -> shuffle list x in place; return None.
278
279 Optional arg random is a 0-argument function returning a random
280 float in [0.0, 1.0); by default, the standard random.random.
Senthil Kumaran37851d02013-09-11 22:52:58 -0700281
282 Do not supply the 'int' argument.
Tim Petersd7b5e882001-01-25 03:36:26 +0000283 """
284
285 if random is None:
286 random = self.random
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000287 for i in reversed(xrange(1, len(x))):
Tim Peterscd804102001-01-25 20:25:57 +0000288 # pick an element in x[:i+1] with which to exchange x[i]
Tim Petersd7b5e882001-01-25 03:36:26 +0000289 j = int(random() * (i+1))
290 x[i], x[j] = x[j], x[i]
291
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000292 def sample(self, population, k):
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000293 """Chooses k unique random elements from a population sequence.
294
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000295 Returns a new list containing elements from the population while
296 leaving the original population unchanged. The resulting list is
297 in selection order so that all sub-slices will also be valid random
298 samples. This allows raffle winners (the sample) to be partitioned
299 into grand prize and second place winners (the subslices).
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000300
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000301 Members of the population need not be hashable or unique. If the
302 population contains repeats, then each occurrence is a possible
303 selection in the sample.
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000304
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000305 To choose a sample in a range of integers, use xrange as an argument.
306 This is especially fast and space efficient for sampling from a
307 large population: sample(xrange(10000000), 60)
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000308 """
309
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000310 # Sampling without replacement entails tracking either potential
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000311 # selections (the pool) in a list or previous selections in a set.
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000312
Jeremy Hylton2b55d352004-02-23 17:27:57 +0000313 # When the number of selections is small compared to the
314 # population, then tracking selections is efficient, requiring
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000315 # only a small set and an occasional reselection. For
Jeremy Hylton2b55d352004-02-23 17:27:57 +0000316 # a larger number of selections, the pool tracking method is
317 # preferred since the list takes less space than the
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000318 # set and it doesn't suffer from frequent reselections.
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000319
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000320 n = len(population)
321 if not 0 <= k <= n:
Raymond Hettinger22d8f7b2011-05-18 17:28:50 -0500322 raise ValueError("sample larger than population")
Raymond Hettinger8b9aa8d2003-01-04 05:20:33 +0000323 random = self.random
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000324 _int = int
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000325 result = [None] * k
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000326 setsize = 21 # size of a small set minus size of an empty list
327 if k > 5:
Tim Peters9e34c042005-08-26 15:20:46 +0000328 setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
Tim Petersc17976e2006-04-01 00:26:53 +0000329 if n <= setsize or hasattr(population, "keys"):
330 # An n-length list is smaller than a k-length set, or this is a
331 # mapping type so the other algorithm wouldn't work.
Raymond Hettinger311f4192002-11-18 09:01:24 +0000332 pool = list(population)
333 for i in xrange(k): # invariant: non-selected at [0,n-i)
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000334 j = _int(random() * (n-i))
Raymond Hettinger311f4192002-11-18 09:01:24 +0000335 result[i] = pool[j]
Raymond Hettinger8b9aa8d2003-01-04 05:20:33 +0000336 pool[j] = pool[n-i-1] # move non-selected item into vacancy
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000337 else:
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000338 try:
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000339 selected = set()
340 selected_add = selected.add
341 for i in xrange(k):
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000342 j = _int(random() * n)
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000343 while j in selected:
344 j = _int(random() * n)
345 selected_add(j)
346 result[i] = population[j]
Tim Petersc17976e2006-04-01 00:26:53 +0000347 except (TypeError, KeyError): # handle (at least) sets
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000348 if isinstance(population, list):
349 raise
Tim Petersc17976e2006-04-01 00:26:53 +0000350 return self.sample(tuple(population), k)
Raymond Hettinger311f4192002-11-18 09:01:24 +0000351 return result
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000352
Tim Peterscd804102001-01-25 20:25:57 +0000353## -------------------- real-valued distributions -------------------
354
355## -------------------- uniform distribution -------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000356
357 def uniform(self, a, b):
Raymond Hettinger2c0cdca2009-06-11 23:14:53 +0000358 "Get a random number in the range [a, b) or [a, b] depending on rounding."
Tim Petersd7b5e882001-01-25 03:36:26 +0000359 return a + (b-a) * self.random()
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000360
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000361## -------------------- triangular --------------------
362
Raymond Hettingerc4f7bab2008-03-23 19:37:53 +0000363 def triangular(self, low=0.0, high=1.0, mode=None):
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000364 """Triangular distribution.
365
366 Continuous distribution bounded by given lower and upper limits,
367 and having a given mode value in-between.
368
369 http://en.wikipedia.org/wiki/Triangular_distribution
370
371 """
372 u = self.random()
Raymond Hettingerc4f7bab2008-03-23 19:37:53 +0000373 c = 0.5 if mode is None else (mode - low) / (high - low)
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000374 if u > c:
Raymond Hettingerc4f7bab2008-03-23 19:37:53 +0000375 u = 1.0 - u
376 c = 1.0 - c
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000377 low, high = high, low
378 return low + (high - low) * (u * c) ** 0.5
379
Tim Peterscd804102001-01-25 20:25:57 +0000380## -------------------- normal distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000381
Tim Petersd7b5e882001-01-25 03:36:26 +0000382 def normalvariate(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000383 """Normal distribution.
384
385 mu is the mean, and sigma is the standard deviation.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000386
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000387 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000388 # mu = mean, sigma = standard deviation
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000389
Tim Petersd7b5e882001-01-25 03:36:26 +0000390 # Uses Kinderman and Monahan method. Reference: Kinderman,
391 # A.J. and Monahan, J.F., "Computer generation of random
392 # variables using the ratio of uniform deviates", ACM Trans
393 # Math Software, 3, (1977), pp257-260.
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000394
Tim Petersd7b5e882001-01-25 03:36:26 +0000395 random = self.random
Raymond Hettinger42406e62005-04-30 09:02:51 +0000396 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000397 u1 = random()
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000398 u2 = 1.0 - random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000399 z = NV_MAGICCONST*(u1-0.5)/u2
400 zz = z*z/4.0
401 if zz <= -_log(u2):
402 break
403 return mu + z*sigma
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000404
Tim Peterscd804102001-01-25 20:25:57 +0000405## -------------------- lognormal distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000406
407 def lognormvariate(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000408 """Log normal distribution.
409
410 If you take the natural logarithm of this distribution, you'll get a
411 normal distribution with mean mu and standard deviation sigma.
412 mu can have any value, and sigma must be greater than zero.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000413
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000414 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000415 return _exp(self.normalvariate(mu, sigma))
416
Tim Peterscd804102001-01-25 20:25:57 +0000417## -------------------- exponential distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000418
419 def expovariate(self, lambd):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000420 """Exponential distribution.
421
Mark Dickinsone6dc5312009-01-07 17:48:33 +0000422 lambd is 1.0 divided by the desired mean. It should be
423 nonzero. (The parameter would be called "lambda", but that is
424 a reserved word in Python.) Returned values range from 0 to
425 positive infinity if lambd is positive, and from negative
426 infinity to 0 if lambd is negative.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000427
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000428 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000429 # lambd: rate lambd = 1/mean
430 # ('lambda' is a Python reserved word)
431
Raymond Hettingercba87312011-06-25 11:24:35 +0200432 # we use 1-random() instead of random() to preclude the
433 # possibility of taking the log of zero.
434 return -_log(1.0 - self.random())/lambd
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000435
Tim Peterscd804102001-01-25 20:25:57 +0000436## -------------------- von Mises distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000437
Tim Petersd7b5e882001-01-25 03:36:26 +0000438 def vonmisesvariate(self, mu, kappa):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000439 """Circular data distribution.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000440
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000441 mu is the mean angle, expressed in radians between 0 and 2*pi, and
442 kappa is the concentration parameter, which must be greater than or
443 equal to zero. If kappa is equal to zero, this distribution reduces
444 to a uniform random angle over the range 0 to 2*pi.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000445
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000446 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000447 # mu: mean angle (in radians between 0 and 2*pi)
448 # kappa: concentration parameter kappa (>= 0)
449 # if kappa = 0 generate uniform random angle
450
451 # Based upon an algorithm published in: Fisher, N.I.,
452 # "Statistical Analysis of Circular Data", Cambridge
453 # University Press, 1993.
454
455 # Thanks to Magnus Kessler for a correction to the
456 # implementation of step 4.
457
458 random = self.random
459 if kappa <= 1e-6:
460 return TWOPI * random()
461
Serhiy Storchaka65d56392013-02-10 19:27:37 +0200462 s = 0.5 / kappa
463 r = s + _sqrt(1.0 + s * s)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000464
Raymond Hettinger42406e62005-04-30 09:02:51 +0000465 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000466 u1 = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000467 z = _cos(_pi * u1)
Tim Petersd7b5e882001-01-25 03:36:26 +0000468
Serhiy Storchaka65d56392013-02-10 19:27:37 +0200469 d = z / (r + z)
Tim Petersd7b5e882001-01-25 03:36:26 +0000470 u2 = random()
Serhiy Storchaka65d56392013-02-10 19:27:37 +0200471 if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d):
Tim Peters0c9886d2001-01-15 01:18:21 +0000472 break
Tim Petersd7b5e882001-01-25 03:36:26 +0000473
Serhiy Storchaka65d56392013-02-10 19:27:37 +0200474 q = 1.0 / r
475 f = (q + z) / (1.0 + q * z)
Tim Petersd7b5e882001-01-25 03:36:26 +0000476 u3 = random()
477 if u3 > 0.5:
Mark Dickinson9aaeb5e2013-02-10 14:13:40 +0000478 theta = (mu + _acos(f)) % TWOPI
Tim Petersd7b5e882001-01-25 03:36:26 +0000479 else:
Mark Dickinson9aaeb5e2013-02-10 14:13:40 +0000480 theta = (mu - _acos(f)) % TWOPI
Tim Petersd7b5e882001-01-25 03:36:26 +0000481
482 return theta
483
Tim Peterscd804102001-01-25 20:25:57 +0000484## -------------------- gamma distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000485
486 def gammavariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000487 """Gamma distribution. Not the gamma function!
488
489 Conditions on the parameters are alpha > 0 and beta > 0.
490
Raymond Hettinger405a4712011-03-22 15:52:46 -0700491 The probability distribution function is:
492
493 x ** (alpha - 1) * math.exp(-x / beta)
494 pdf(x) = --------------------------------------
495 math.gamma(alpha) * beta ** alpha
496
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000497 """
Tim Peters8ac14952002-05-23 15:15:30 +0000498
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000499 # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
Tim Peters8ac14952002-05-23 15:15:30 +0000500
Guido van Rossum570764d2002-05-14 14:08:12 +0000501 # Warning: a few older sources define the gamma distribution in terms
502 # of alpha > -1.0
503 if alpha <= 0.0 or beta <= 0.0:
504 raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
Tim Peters8ac14952002-05-23 15:15:30 +0000505
Tim Petersd7b5e882001-01-25 03:36:26 +0000506 random = self.random
Tim Petersd7b5e882001-01-25 03:36:26 +0000507 if alpha > 1.0:
508
509 # Uses R.C.H. Cheng, "The generation of Gamma
510 # variables with non-integral shape parameters",
511 # Applied Statistics, (1977), 26, No. 1, p71-74
512
Raymond Hettingerca6cdc22002-05-13 23:40:14 +0000513 ainv = _sqrt(2.0 * alpha - 1.0)
514 bbb = alpha - LOG4
515 ccc = alpha + ainv
Tim Peters8ac14952002-05-23 15:15:30 +0000516
Raymond Hettinger42406e62005-04-30 09:02:51 +0000517 while 1:
Tim Petersd7b5e882001-01-25 03:36:26 +0000518 u1 = random()
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000519 if not 1e-7 < u1 < .9999999:
520 continue
521 u2 = 1.0 - random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000522 v = _log(u1/(1.0-u1))/ainv
523 x = alpha*_exp(v)
524 z = u1*u1*u2
525 r = bbb+ccc*v-x
526 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000527 return x * beta
Tim Petersd7b5e882001-01-25 03:36:26 +0000528
529 elif alpha == 1.0:
530 # expovariate(1)
531 u = random()
532 while u <= 1e-7:
533 u = random()
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000534 return -_log(u) * beta
Tim Petersd7b5e882001-01-25 03:36:26 +0000535
536 else: # alpha is between 0 and 1 (exclusive)
537
538 # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
539
Raymond Hettinger42406e62005-04-30 09:02:51 +0000540 while 1:
Tim Petersd7b5e882001-01-25 03:36:26 +0000541 u = random()
542 b = (_e + alpha)/_e
543 p = b*u
544 if p <= 1.0:
Raymond Hettinger42406e62005-04-30 09:02:51 +0000545 x = p ** (1.0/alpha)
Tim Petersd7b5e882001-01-25 03:36:26 +0000546 else:
Tim Petersd7b5e882001-01-25 03:36:26 +0000547 x = -_log((b-p)/alpha)
548 u1 = random()
Raymond Hettinger42406e62005-04-30 09:02:51 +0000549 if p > 1.0:
550 if u1 <= x ** (alpha - 1.0):
551 break
552 elif u1 <= _exp(-x):
Tim Petersd7b5e882001-01-25 03:36:26 +0000553 break
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000554 return x * beta
555
Tim Peterscd804102001-01-25 20:25:57 +0000556## -------------------- Gauss (faster alternative) --------------------
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000557
Tim Petersd7b5e882001-01-25 03:36:26 +0000558 def gauss(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000559 """Gaussian distribution.
560
561 mu is the mean, and sigma is the standard deviation. This is
562 slightly faster than the normalvariate() function.
563
564 Not thread-safe without a lock around calls.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000565
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000566 """
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000567
Tim Petersd7b5e882001-01-25 03:36:26 +0000568 # When x and y are two variables from [0, 1), uniformly
569 # distributed, then
570 #
571 # cos(2*pi*x)*sqrt(-2*log(1-y))
572 # sin(2*pi*x)*sqrt(-2*log(1-y))
573 #
574 # are two *independent* variables with normal distribution
575 # (mu = 0, sigma = 1).
576 # (Lambert Meertens)
577 # (corrected version; bug discovered by Mike Miller, fixed by LM)
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000578
Tim Petersd7b5e882001-01-25 03:36:26 +0000579 # Multithreading note: When two threads call this function
580 # simultaneously, it is possible that they will receive the
581 # same return value. The window is very small though. To
582 # avoid this, you have to use a lock around all calls. (I
583 # didn't want to slow this down in the serial case by using a
584 # lock here.)
Guido van Rossumd03e1191998-05-29 17:51:31 +0000585
Tim Petersd7b5e882001-01-25 03:36:26 +0000586 random = self.random
587 z = self.gauss_next
588 self.gauss_next = None
589 if z is None:
590 x2pi = random() * TWOPI
591 g2rad = _sqrt(-2.0 * _log(1.0 - random()))
592 z = _cos(x2pi) * g2rad
593 self.gauss_next = _sin(x2pi) * g2rad
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000594
Tim Petersd7b5e882001-01-25 03:36:26 +0000595 return mu + z*sigma
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000596
Tim Peterscd804102001-01-25 20:25:57 +0000597## -------------------- beta --------------------
Tim Peters85e2e472001-01-26 06:49:56 +0000598## See
Ezio Melotti1bb18cc2011-04-15 08:25:16 +0300599## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html
Tim Peters85e2e472001-01-26 06:49:56 +0000600## for Ivan Frohne's insightful analysis of why the original implementation:
601##
602## def betavariate(self, alpha, beta):
603## # Discrete Event Simulation in C, pp 87-88.
604##
605## y = self.expovariate(alpha)
606## z = self.expovariate(1.0/beta)
607## return z/(y+z)
608##
609## was dead wrong, and how it probably got that way.
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000610
Tim Petersd7b5e882001-01-25 03:36:26 +0000611 def betavariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000612 """Beta distribution.
613
Raymond Hettinger1b0ce852007-01-19 18:07:18 +0000614 Conditions on the parameters are alpha > 0 and beta > 0.
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000615 Returned values range between 0 and 1.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000616
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000617 """
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000618
Tim Peters85e2e472001-01-26 06:49:56 +0000619 # This version due to Janne Sinkkonen, and matches all the std
620 # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
621 y = self.gammavariate(alpha, 1.)
622 if y == 0:
623 return 0.0
624 else:
625 return y / (y + self.gammavariate(beta, 1.))
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000626
Tim Peterscd804102001-01-25 20:25:57 +0000627## -------------------- Pareto --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000628
Tim Petersd7b5e882001-01-25 03:36:26 +0000629 def paretovariate(self, alpha):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000630 """Pareto distribution. alpha is the shape parameter."""
Tim Petersd7b5e882001-01-25 03:36:26 +0000631 # Jain, pg. 495
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000632
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000633 u = 1.0 - self.random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000634 return 1.0 / pow(u, 1.0/alpha)
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000635
Tim Peterscd804102001-01-25 20:25:57 +0000636## -------------------- Weibull --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000637
Tim Petersd7b5e882001-01-25 03:36:26 +0000638 def weibullvariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000639 """Weibull distribution.
640
641 alpha is the scale parameter and beta is the shape parameter.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000642
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000643 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000644 # Jain, pg. 499; bug fix courtesy Bill Arms
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000645
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000646 u = 1.0 - self.random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000647 return alpha * pow(-_log(u), 1.0/beta)
Guido van Rossum6c395ba1999-08-18 13:53:28 +0000648
Raymond Hettinger40f62172002-12-29 23:03:38 +0000649## -------------------- Wichmann-Hill -------------------
650
651class WichmannHill(Random):
652
653 VERSION = 1 # used by getstate/setstate
654
655 def seed(self, a=None):
656 """Initialize internal state from hashable object.
657
Raymond Hettinger23f12412004-09-13 22:23:21 +0000658 None or no argument seeds from current time or from an operating
659 system specific randomness source if available.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000660
661 If a is not None or an int or long, hash(a) is used instead.
662
663 If a is an int or long, a is used directly. Distinct values between
664 0 and 27814431486575L inclusive are guaranteed to yield distinct
665 internal states (this guarantee is specific to the default
666 Wichmann-Hill generator).
667 """
668
669 if a is None:
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000670 try:
671 a = long(_hexlify(_urandom(16)), 16)
672 except NotImplementedError:
Raymond Hettinger356a4592004-08-30 06:14:31 +0000673 import time
674 a = long(time.time() * 256) # use fractional seconds
Raymond Hettinger40f62172002-12-29 23:03:38 +0000675
676 if not isinstance(a, (int, long)):
677 a = hash(a)
678
679 a, x = divmod(a, 30268)
680 a, y = divmod(a, 30306)
681 a, z = divmod(a, 30322)
682 self._seed = int(x)+1, int(y)+1, int(z)+1
683
684 self.gauss_next = None
685
686 def random(self):
687 """Get the next random number in the range [0.0, 1.0)."""
688
689 # Wichman-Hill random number generator.
690 #
691 # Wichmann, B. A. & Hill, I. D. (1982)
692 # Algorithm AS 183:
693 # An efficient and portable pseudo-random number generator
694 # Applied Statistics 31 (1982) 188-190
695 #
696 # see also:
697 # Correction to Algorithm AS 183
698 # Applied Statistics 33 (1984) 123
699 #
700 # McLeod, A. I. (1985)
701 # A remark on Algorithm AS 183
702 # Applied Statistics 34 (1985),198-200
703
704 # This part is thread-unsafe:
705 # BEGIN CRITICAL SECTION
706 x, y, z = self._seed
707 x = (171 * x) % 30269
708 y = (172 * y) % 30307
709 z = (170 * z) % 30323
710 self._seed = x, y, z
711 # END CRITICAL SECTION
712
713 # Note: on a platform using IEEE-754 double arithmetic, this can
714 # never return 0.0 (asserted by Tim; proof too long for a comment).
715 return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
716
717 def getstate(self):
718 """Return internal state; can be passed to setstate() later."""
719 return self.VERSION, self._seed, self.gauss_next
720
721 def setstate(self, state):
722 """Restore internal state from object returned by getstate()."""
723 version = state[0]
724 if version == 1:
725 version, self._seed, self.gauss_next = state
726 else:
727 raise ValueError("state with version %s passed to "
728 "Random.setstate() of version %s" %
729 (version, self.VERSION))
730
731 def jumpahead(self, n):
732 """Act as if n calls to random() were made, but quickly.
733
734 n is an int, greater than or equal to 0.
735
736 Example use: If you have 2 threads and know that each will
737 consume no more than a million random numbers, create two Random
738 objects r1 and r2, then do
739 r2.setstate(r1.getstate())
740 r2.jumpahead(1000000)
741 Then r1 and r2 will use guaranteed-disjoint segments of the full
742 period.
743 """
744
745 if not n >= 0:
746 raise ValueError("n must be >= 0")
747 x, y, z = self._seed
748 x = int(x * pow(171, n, 30269)) % 30269
749 y = int(y * pow(172, n, 30307)) % 30307
750 z = int(z * pow(170, n, 30323)) % 30323
751 self._seed = x, y, z
752
753 def __whseed(self, x=0, y=0, z=0):
754 """Set the Wichmann-Hill seed from (x, y, z).
755
756 These must be integers in the range [0, 256).
757 """
758
759 if not type(x) == type(y) == type(z) == int:
760 raise TypeError('seeds must be integers')
761 if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256):
762 raise ValueError('seeds must be in range(0, 256)')
763 if 0 == x == y == z:
764 # Initialize from current time
765 import time
766 t = long(time.time() * 256)
767 t = int((t&0xffffff) ^ (t>>24))
768 t, x = divmod(t, 256)
769 t, y = divmod(t, 256)
770 t, z = divmod(t, 256)
771 # Zero is a poor seed, so substitute 1
772 self._seed = (x or 1, y or 1, z or 1)
773
774 self.gauss_next = None
775
776 def whseed(self, a=None):
777 """Seed from hashable object's hash code.
778
779 None or no argument seeds from current time. It is not guaranteed
780 that objects with distinct hash codes lead to distinct internal
781 states.
782
783 This is obsolete, provided for compatibility with the seed routine
784 used prior to Python 2.1. Use the .seed() method instead.
785 """
786
787 if a is None:
788 self.__whseed()
789 return
790 a = hash(a)
791 a, x = divmod(a, 256)
792 a, y = divmod(a, 256)
793 a, z = divmod(a, 256)
794 x = (x + a) % 256 or 1
795 y = (y + a) % 256 or 1
796 z = (z + a) % 256 or 1
797 self.__whseed(x, y, z)
798
Raymond Hettinger23f12412004-09-13 22:23:21 +0000799## --------------- Operating System Random Source ------------------
Raymond Hettinger356a4592004-08-30 06:14:31 +0000800
Raymond Hettinger23f12412004-09-13 22:23:21 +0000801class SystemRandom(Random):
802 """Alternate random number generator using sources provided
803 by the operating system (such as /dev/urandom on Unix or
804 CryptGenRandom on Windows).
Raymond Hettinger356a4592004-08-30 06:14:31 +0000805
806 Not available on all systems (see os.urandom() for details).
807 """
808
809 def random(self):
810 """Get the next random number in the range [0.0, 1.0)."""
Tim Peters7c2a85b2004-08-31 02:19:55 +0000811 return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Raymond Hettinger356a4592004-08-30 06:14:31 +0000812
813 def getrandbits(self, k):
814 """getrandbits(k) -> x. Generates a long int with k random bits."""
Raymond Hettinger356a4592004-08-30 06:14:31 +0000815 if k <= 0:
816 raise ValueError('number of bits must be greater than zero')
817 if k != int(k):
818 raise TypeError('number of bits should be an integer')
819 bytes = (k + 7) // 8 # bits / 8 and rounded up
820 x = long(_hexlify(_urandom(bytes)), 16)
821 return x >> (bytes * 8 - k) # trim excess bits
822
823 def _stub(self, *args, **kwds):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000824 "Stub method. Not used for a system random number generator."
Raymond Hettinger356a4592004-08-30 06:14:31 +0000825 return None
826 seed = jumpahead = _stub
827
828 def _notimplemented(self, *args, **kwds):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000829 "Method should not be called for a system random number generator."
830 raise NotImplementedError('System entropy source does not have state.')
Raymond Hettinger356a4592004-08-30 06:14:31 +0000831 getstate = setstate = _notimplemented
832
Tim Peterscd804102001-01-25 20:25:57 +0000833## -------------------- test program --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000834
Raymond Hettinger62297132003-08-30 01:24:19 +0000835def _test_generator(n, func, args):
Tim Peters0c9886d2001-01-15 01:18:21 +0000836 import time
Raymond Hettinger62297132003-08-30 01:24:19 +0000837 print n, 'times', func.__name__
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000838 total = 0.0
Tim Peters0c9886d2001-01-15 01:18:21 +0000839 sqsum = 0.0
840 smallest = 1e10
841 largest = -1e10
842 t0 = time.time()
843 for i in range(n):
Raymond Hettinger62297132003-08-30 01:24:19 +0000844 x = func(*args)
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000845 total += x
Tim Peters0c9886d2001-01-15 01:18:21 +0000846 sqsum = sqsum + x*x
847 smallest = min(x, smallest)
848 largest = max(x, largest)
849 t1 = time.time()
850 print round(t1-t0, 3), 'sec,',
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000851 avg = total/n
Tim Petersd7b5e882001-01-25 03:36:26 +0000852 stddev = _sqrt(sqsum/n - avg*avg)
Tim Peters0c9886d2001-01-15 01:18:21 +0000853 print 'avg %g, stddev %g, min %g, max %g' % \
854 (avg, stddev, smallest, largest)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000855
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000856
857def _test(N=2000):
Raymond Hettinger62297132003-08-30 01:24:19 +0000858 _test_generator(N, random, ())
859 _test_generator(N, normalvariate, (0.0, 1.0))
860 _test_generator(N, lognormvariate, (0.0, 1.0))
861 _test_generator(N, vonmisesvariate, (0.0, 1.0))
862 _test_generator(N, gammavariate, (0.01, 1.0))
863 _test_generator(N, gammavariate, (0.1, 1.0))
864 _test_generator(N, gammavariate, (0.1, 2.0))
865 _test_generator(N, gammavariate, (0.5, 1.0))
866 _test_generator(N, gammavariate, (0.9, 1.0))
867 _test_generator(N, gammavariate, (1.0, 1.0))
868 _test_generator(N, gammavariate, (2.0, 1.0))
869 _test_generator(N, gammavariate, (20.0, 1.0))
870 _test_generator(N, gammavariate, (200.0, 1.0))
871 _test_generator(N, gauss, (0.0, 1.0))
872 _test_generator(N, betavariate, (3.0, 3.0))
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000873 _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0))
Tim Peterscd804102001-01-25 20:25:57 +0000874
Tim Peters715c4c42001-01-26 22:56:56 +0000875# Create one instance, seeded from current time, and export its methods
Raymond Hettinger40f62172002-12-29 23:03:38 +0000876# as module-level functions. The functions share state across all uses
877#(both in the user's code and in the Python libraries), but that's fine
878# for most programs and is easier for the casual user than making them
879# instantiate their own Random() instance.
880
Tim Petersd7b5e882001-01-25 03:36:26 +0000881_inst = Random()
882seed = _inst.seed
883random = _inst.random
884uniform = _inst.uniform
Raymond Hettingerbbc50ea2008-03-23 13:32:32 +0000885triangular = _inst.triangular
Tim Petersd7b5e882001-01-25 03:36:26 +0000886randint = _inst.randint
887choice = _inst.choice
888randrange = _inst.randrange
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000889sample = _inst.sample
Tim Petersd7b5e882001-01-25 03:36:26 +0000890shuffle = _inst.shuffle
891normalvariate = _inst.normalvariate
892lognormvariate = _inst.lognormvariate
Tim Petersd7b5e882001-01-25 03:36:26 +0000893expovariate = _inst.expovariate
894vonmisesvariate = _inst.vonmisesvariate
895gammavariate = _inst.gammavariate
Tim Petersd7b5e882001-01-25 03:36:26 +0000896gauss = _inst.gauss
897betavariate = _inst.betavariate
898paretovariate = _inst.paretovariate
899weibullvariate = _inst.weibullvariate
900getstate = _inst.getstate
901setstate = _inst.setstate
Tim Petersd52269b2001-01-25 06:23:18 +0000902jumpahead = _inst.jumpahead
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000903getrandbits = _inst.getrandbits
Tim Petersd7b5e882001-01-25 03:36:26 +0000904
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000905if __name__ == '__main__':
Tim Petersd7b5e882001-01-25 03:36:26 +0000906 _test()