blob: ec0f3868b690dc2acb4d4680f68898d9b3309786 [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
Guido van Rossume7b146f2000-02-04 15:28:42 +000016 normal (Gaussian)
17 lognormal
18 negative exponential
19 gamma
20 beta
Raymond Hettinger40f62172002-12-29 23:03:38 +000021 pareto
22 Weibull
Guido van Rossumff03b1a1994-03-09 12:55:02 +000023
Guido van Rossume7b146f2000-02-04 15:28:42 +000024 distributions on the circle (angles 0 to 2pi)
25 ---------------------------------------------
26 circular uniform
27 von Mises
28
Raymond Hettinger40f62172002-12-29 23:03:38 +000029General notes on the underlying Mersenne Twister core generator:
Guido van Rossume7b146f2000-02-04 15:28:42 +000030
Raymond Hettinger40f62172002-12-29 23:03:38 +000031* The period is 2**19937-1.
Tim Peters0e115952006-06-10 22:51:45 +000032* It is one of the most extensively tested generators in existence.
33* Without a direct way to compute N steps forward, the semantics of
34 jumpahead(n) are weakened to simply jump to another distant state and rely
35 on the large period to avoid overlapping sequences.
36* The random() method is implemented in C, executes in a single Python step,
37 and is, therefore, threadsafe.
Tim Peterse360d952001-01-26 10:00:39 +000038
Guido van Rossume7b146f2000-02-04 15:28:42 +000039"""
Guido van Rossumd03e1191998-05-29 17:51:31 +000040
Raymond Hettinger2f726e92003-10-05 09:09:15 +000041from warnings import warn as _warn
42from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType
Raymond Hettinger91e27c22005-08-19 01:36:35 +000043from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
Tim Petersd7b5e882001-01-25 03:36:26 +000044from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +000045from os import urandom as _urandom
46from binascii import hexlify as _hexlify
Guido van Rossumff03b1a1994-03-09 12:55:02 +000047
Raymond Hettingerf24eb352002-11-12 17:41:57 +000048__all__ = ["Random","seed","random","uniform","randint","choice","sample",
Skip Montanaro0de65802001-02-15 22:15:14 +000049 "randrange","shuffle","normalvariate","lognormvariate",
Raymond Hettingerf8a52d32003-08-05 12:23:19 +000050 "expovariate","vonmisesvariate","gammavariate",
51 "gauss","betavariate","paretovariate","weibullvariate",
Raymond Hettinger356a4592004-08-30 06:14:31 +000052 "getstate","setstate","jumpahead", "WichmannHill", "getrandbits",
Raymond Hettinger23f12412004-09-13 22:23:21 +000053 "SystemRandom"]
Tim Petersd7b5e882001-01-25 03:36:26 +000054
55NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
Tim Petersd7b5e882001-01-25 03:36:26 +000056TWOPI = 2.0*_pi
Tim Petersd7b5e882001-01-25 03:36:26 +000057LOG4 = _log(4.0)
Tim Petersd7b5e882001-01-25 03:36:26 +000058SG_MAGICCONST = 1.0 + _log(4.5)
Raymond Hettinger2f726e92003-10-05 09:09:15 +000059BPF = 53 # Number of bits in a float
Tim Peters7c2a85b2004-08-31 02:19:55 +000060RECIP_BPF = 2**-BPF
Tim Petersd7b5e882001-01-25 03:36:26 +000061
Raymond Hettinger356a4592004-08-30 06:14:31 +000062
Tim Petersd7b5e882001-01-25 03:36:26 +000063# Translated by Guido van Rossum from C source provided by
Raymond Hettinger40f62172002-12-29 23:03:38 +000064# Adrian Baddeley. Adapted by Raymond Hettinger for use with
Raymond Hettinger3fa19d72004-08-31 01:05:15 +000065# the Mersenne Twister and os.urandom() core generators.
Tim Petersd7b5e882001-01-25 03:36:26 +000066
Raymond Hettinger145a4a02003-01-07 10:25:55 +000067import _random
Raymond Hettinger40f62172002-12-29 23:03:38 +000068
Raymond Hettinger145a4a02003-01-07 10:25:55 +000069class Random(_random.Random):
Raymond Hettingerc32f0332002-05-23 19:44:49 +000070 """Random number generator base class used by bound module functions.
71
72 Used to instantiate instances of Random to get generators that don't
73 share state. Especially useful for multi-threaded programs, creating
74 a different instance of Random for each thread, and using the jumpahead()
75 method to ensure that the generated sequences seen by each thread don't
76 overlap.
77
78 Class Random can also be subclassed if you want to use a different basic
79 generator of your own devising: in that case, override the following
80 methods: random(), seed(), getstate(), setstate() and jumpahead().
Raymond Hettinger2f726e92003-10-05 09:09:15 +000081 Optionally, implement a getrandombits() method so that randrange()
82 can cover arbitrarily large ranges.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +000083
Raymond Hettingerc32f0332002-05-23 19:44:49 +000084 """
Tim Petersd7b5e882001-01-25 03:36:26 +000085
Martin v. Löwis6b449f42007-12-03 19:20:02 +000086 VERSION = 3 # used by getstate/setstate
Tim Petersd7b5e882001-01-25 03:36:26 +000087
88 def __init__(self, x=None):
89 """Initialize an instance.
90
91 Optional argument x controls seeding, as for Random.seed().
92 """
93
94 self.seed(x)
Raymond Hettinger40f62172002-12-29 23:03:38 +000095 self.gauss_next = None
Tim Petersd7b5e882001-01-25 03:36:26 +000096
Tim Peters0de88fc2001-02-01 04:59:18 +000097 def seed(self, a=None):
98 """Initialize internal state from hashable object.
Tim Petersd7b5e882001-01-25 03:36:26 +000099
Raymond Hettinger23f12412004-09-13 22:23:21 +0000100 None or no argument seeds from current time or from an operating
101 system specific randomness source if available.
Tim Peters0de88fc2001-02-01 04:59:18 +0000102
Tim Petersbcd725f2001-02-01 10:06:53 +0000103 If a is not None or an int or long, hash(a) is used instead.
Tim Petersd7b5e882001-01-25 03:36:26 +0000104 """
105
Raymond Hettinger3081d592003-08-09 18:30:57 +0000106 if a is None:
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000107 try:
108 a = long(_hexlify(_urandom(16)), 16)
109 except NotImplementedError:
Raymond Hettinger356a4592004-08-30 06:14:31 +0000110 import time
111 a = long(time.time() * 256) # use fractional seconds
Raymond Hettinger356a4592004-08-30 06:14:31 +0000112
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000113 super(Random, self).seed(a)
Tim Peters46c04e12002-05-05 20:40:00 +0000114 self.gauss_next = None
115
Tim Peterscd804102001-01-25 20:25:57 +0000116 def getstate(self):
117 """Return internal state; can be passed to setstate() later."""
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000118 return self.VERSION, super(Random, self).getstate(), self.gauss_next
Tim Peterscd804102001-01-25 20:25:57 +0000119
120 def setstate(self, state):
121 """Restore internal state from object returned by getstate()."""
122 version = state[0]
Martin v. Löwis6b449f42007-12-03 19:20:02 +0000123 if version == 3:
Raymond Hettinger40f62172002-12-29 23:03:38 +0000124 version, internalstate, self.gauss_next = state
Raymond Hettinger145a4a02003-01-07 10:25:55 +0000125 super(Random, self).setstate(internalstate)
Martin v. Löwis6b449f42007-12-03 19:20:02 +0000126 elif version == 2:
127 version, internalstate, self.gauss_next = state
128 # In version 2, the state was saved as signed ints, which causes
129 # inconsistencies between 32/64-bit systems. The state is
130 # really unsigned 32-bit ints, so we convert negative ints from
131 # version 2 to positive longs for version 3.
132 try:
133 internalstate = tuple( long(x) % (2**32) for x in internalstate )
134 except ValueError, e:
135 raise TypeError, e
136 super(Random, self).setstate(internalstate)
Tim Peterscd804102001-01-25 20:25:57 +0000137 else:
138 raise ValueError("state with version %s passed to "
139 "Random.setstate() of version %s" %
140 (version, self.VERSION))
141
Tim Peterscd804102001-01-25 20:25:57 +0000142## ---- Methods below this point do not need to be overridden when
143## ---- subclassing for the purpose of using a different core generator.
144
145## -------------------- pickle support -------------------
146
147 def __getstate__(self): # for pickle
148 return self.getstate()
149
150 def __setstate__(self, state): # for pickle
151 self.setstate(state)
152
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000153 def __reduce__(self):
154 return self.__class__, (), self.getstate()
155
Tim Peterscd804102001-01-25 20:25:57 +0000156## -------------------- integer methods -------------------
157
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000158 def randrange(self, start, stop=None, step=1, int=int, default=None,
159 maxwidth=1L<<BPF):
Tim Petersd7b5e882001-01-25 03:36:26 +0000160 """Choose a random item from range(start, stop[, step]).
161
162 This fixes the problem with randint() which includes the
163 endpoint; in Python this is usually not what you want.
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000164 Do not supply the 'int', 'default', and 'maxwidth' arguments.
Tim Petersd7b5e882001-01-25 03:36:26 +0000165 """
166
167 # This code is a bit messy to make it fast for the
Tim Peters9146f272002-08-16 03:41:39 +0000168 # common case while still doing adequate error checking.
Tim Petersd7b5e882001-01-25 03:36:26 +0000169 istart = int(start)
170 if istart != start:
171 raise ValueError, "non-integer arg 1 for randrange()"
172 if stop is default:
173 if istart > 0:
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000174 if istart >= maxwidth:
175 return self._randbelow(istart)
Tim Petersd7b5e882001-01-25 03:36:26 +0000176 return int(self.random() * istart)
177 raise ValueError, "empty range for randrange()"
Tim Peters9146f272002-08-16 03:41:39 +0000178
179 # stop argument supplied.
Tim Petersd7b5e882001-01-25 03:36:26 +0000180 istop = int(stop)
181 if istop != stop:
182 raise ValueError, "non-integer stop for randrange()"
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000183 width = istop - istart
184 if step == 1 and width > 0:
Tim Peters76ca1d42003-06-19 03:46:46 +0000185 # Note that
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000186 # int(istart + self.random()*width)
Tim Peters76ca1d42003-06-19 03:46:46 +0000187 # instead would be incorrect. For example, consider istart
188 # = -2 and istop = 0. Then the guts would be in
189 # -2.0 to 0.0 exclusive on both ends (ignoring that random()
190 # might return 0.0), and because int() truncates toward 0, the
191 # final result would be -1 or 0 (instead of -2 or -1).
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000192 # istart + int(self.random()*width)
Tim Peters76ca1d42003-06-19 03:46:46 +0000193 # would also be incorrect, for a subtler reason: the RHS
194 # can return a long, and then randrange() would also return
195 # a long, but we're supposed to return an int (for backward
196 # compatibility).
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000197
198 if width >= maxwidth:
Tim Peters58eb11c2004-01-18 20:29:55 +0000199 return int(istart + self._randbelow(width))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000200 return int(istart + int(self.random()*width))
Tim Petersd7b5e882001-01-25 03:36:26 +0000201 if step == 1:
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000202 raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
Tim Peters9146f272002-08-16 03:41:39 +0000203
204 # Non-unit step argument supplied.
Tim Petersd7b5e882001-01-25 03:36:26 +0000205 istep = int(step)
206 if istep != step:
207 raise ValueError, "non-integer step for randrange()"
208 if istep > 0:
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000209 n = (width + istep - 1) // istep
Tim Petersd7b5e882001-01-25 03:36:26 +0000210 elif istep < 0:
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000211 n = (width + istep + 1) // istep
Tim Petersd7b5e882001-01-25 03:36:26 +0000212 else:
213 raise ValueError, "zero step for randrange()"
214
215 if n <= 0:
216 raise ValueError, "empty range for randrange()"
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000217
218 if n >= maxwidth:
Raymond Hettinger94547f72006-12-20 06:42:06 +0000219 return istart + istep*self._randbelow(n)
Tim Petersd7b5e882001-01-25 03:36:26 +0000220 return istart + istep*int(self.random() * n)
221
222 def randint(self, a, b):
Tim Peterscd804102001-01-25 20:25:57 +0000223 """Return random integer in range [a, b], including both end points.
Tim Petersd7b5e882001-01-25 03:36:26 +0000224 """
225
226 return self.randrange(a, b+1)
227
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000228 def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L<<BPF,
229 _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
230 """Return a random int in the range [0,n)
231
232 Handles the case where n has more bits than returned
233 by a single call to the underlying generator.
234 """
235
236 try:
237 getrandbits = self.getrandbits
238 except AttributeError:
239 pass
240 else:
241 # Only call self.getrandbits if the original random() builtin method
242 # has not been overridden or if a new getrandbits() was supplied.
243 # This assures that the two methods correspond.
244 if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
245 k = int(1.00001 + _log(n-1, 2.0)) # 2**k > n-1 > 2**(k-2)
246 r = getrandbits(k)
247 while r >= n:
248 r = getrandbits(k)
249 return r
250 if n >= _maxwidth:
251 _warn("Underlying random() generator does not supply \n"
252 "enough bits to choose from a population range this large")
253 return int(self.random() * n)
254
Tim Peterscd804102001-01-25 20:25:57 +0000255## -------------------- sequence methods -------------------
256
Tim Petersd7b5e882001-01-25 03:36:26 +0000257 def choice(self, seq):
258 """Choose a random element from a non-empty sequence."""
Raymond Hettinger5dae5052004-06-07 02:07:15 +0000259 return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
Tim Petersd7b5e882001-01-25 03:36:26 +0000260
261 def shuffle(self, x, random=None, int=int):
262 """x, random=random.random -> shuffle list x in place; return None.
263
264 Optional arg random is a 0-argument function returning a random
265 float in [0.0, 1.0); by default, the standard random.random.
Tim Petersd7b5e882001-01-25 03:36:26 +0000266 """
267
268 if random is None:
269 random = self.random
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000270 for i in reversed(xrange(1, len(x))):
Tim Peterscd804102001-01-25 20:25:57 +0000271 # pick an element in x[:i+1] with which to exchange x[i]
Tim Petersd7b5e882001-01-25 03:36:26 +0000272 j = int(random() * (i+1))
273 x[i], x[j] = x[j], x[i]
274
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000275 def sample(self, population, k):
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000276 """Chooses k unique random elements from a population sequence.
277
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000278 Returns a new list containing elements from the population while
279 leaving the original population unchanged. The resulting list is
280 in selection order so that all sub-slices will also be valid random
281 samples. This allows raffle winners (the sample) to be partitioned
282 into grand prize and second place winners (the subslices).
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000283
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000284 Members of the population need not be hashable or unique. If the
285 population contains repeats, then each occurrence is a possible
286 selection in the sample.
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000287
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000288 To choose a sample in a range of integers, use xrange as an argument.
289 This is especially fast and space efficient for sampling from a
290 large population: sample(xrange(10000000), 60)
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000291 """
292
Tim Petersc17976e2006-04-01 00:26:53 +0000293 # XXX Although the documentation says `population` is "a sequence",
294 # XXX attempts are made to cater to any iterable with a __len__
295 # XXX method. This has had mixed success. Examples from both
296 # XXX sides: sets work fine, and should become officially supported;
297 # XXX dicts are much harder, and have failed in various subtle
298 # XXX ways across attempts. Support for mapping types should probably
299 # XXX be dropped (and users should pass mapping.keys() or .values()
300 # XXX explicitly).
301
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000302 # Sampling without replacement entails tracking either potential
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000303 # selections (the pool) in a list or previous selections in a set.
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000304
Jeremy Hylton2b55d352004-02-23 17:27:57 +0000305 # When the number of selections is small compared to the
306 # population, then tracking selections is efficient, requiring
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000307 # only a small set and an occasional reselection. For
Jeremy Hylton2b55d352004-02-23 17:27:57 +0000308 # a larger number of selections, the pool tracking method is
309 # preferred since the list takes less space than the
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000310 # set and it doesn't suffer from frequent reselections.
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000311
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000312 n = len(population)
313 if not 0 <= k <= n:
314 raise ValueError, "sample larger than population"
Raymond Hettinger8b9aa8d2003-01-04 05:20:33 +0000315 random = self.random
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000316 _int = int
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000317 result = [None] * k
Raymond Hettinger91e27c22005-08-19 01:36:35 +0000318 setsize = 21 # size of a small set minus size of an empty list
319 if k > 5:
Tim Peters9e34c042005-08-26 15:20:46 +0000320 setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
Tim Petersc17976e2006-04-01 00:26:53 +0000321 if n <= setsize or hasattr(population, "keys"):
322 # An n-length list is smaller than a k-length set, or this is a
323 # mapping type so the other algorithm wouldn't work.
Raymond Hettinger311f4192002-11-18 09:01:24 +0000324 pool = list(population)
325 for i in xrange(k): # invariant: non-selected at [0,n-i)
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000326 j = _int(random() * (n-i))
Raymond Hettinger311f4192002-11-18 09:01:24 +0000327 result[i] = pool[j]
Raymond Hettinger8b9aa8d2003-01-04 05:20:33 +0000328 pool[j] = pool[n-i-1] # move non-selected item into vacancy
Raymond Hettingerc0b40342002-11-13 15:26:37 +0000329 else:
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000330 try:
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000331 selected = set()
332 selected_add = selected.add
333 for i in xrange(k):
Raymond Hettingerfdbe5222003-06-13 07:01:51 +0000334 j = _int(random() * n)
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000335 while j in selected:
336 j = _int(random() * n)
337 selected_add(j)
338 result[i] = population[j]
Tim Petersc17976e2006-04-01 00:26:53 +0000339 except (TypeError, KeyError): # handle (at least) sets
Raymond Hettinger3c3346d2006-03-29 09:13:13 +0000340 if isinstance(population, list):
341 raise
Tim Petersc17976e2006-04-01 00:26:53 +0000342 return self.sample(tuple(population), k)
Raymond Hettinger311f4192002-11-18 09:01:24 +0000343 return result
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000344
Tim Peterscd804102001-01-25 20:25:57 +0000345## -------------------- real-valued distributions -------------------
346
347## -------------------- uniform distribution -------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000348
349 def uniform(self, a, b):
350 """Get a random number in the range [a, b)."""
351 return a + (b-a) * self.random()
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000352
Tim Peterscd804102001-01-25 20:25:57 +0000353## -------------------- normal distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000354
Tim Petersd7b5e882001-01-25 03:36:26 +0000355 def normalvariate(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000356 """Normal distribution.
357
358 mu is the mean, and sigma is the standard deviation.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000359
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000360 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000361 # mu = mean, sigma = standard deviation
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000362
Tim Petersd7b5e882001-01-25 03:36:26 +0000363 # Uses Kinderman and Monahan method. Reference: Kinderman,
364 # A.J. and Monahan, J.F., "Computer generation of random
365 # variables using the ratio of uniform deviates", ACM Trans
366 # Math Software, 3, (1977), pp257-260.
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000367
Tim Petersd7b5e882001-01-25 03:36:26 +0000368 random = self.random
Raymond Hettinger42406e62005-04-30 09:02:51 +0000369 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000370 u1 = random()
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000371 u2 = 1.0 - random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000372 z = NV_MAGICCONST*(u1-0.5)/u2
373 zz = z*z/4.0
374 if zz <= -_log(u2):
375 break
376 return mu + z*sigma
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000377
Tim Peterscd804102001-01-25 20:25:57 +0000378## -------------------- lognormal distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000379
380 def lognormvariate(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000381 """Log normal distribution.
382
383 If you take the natural logarithm of this distribution, you'll get a
384 normal distribution with mean mu and standard deviation sigma.
385 mu can have any value, and sigma must be greater than zero.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000386
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000387 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000388 return _exp(self.normalvariate(mu, sigma))
389
Tim Peterscd804102001-01-25 20:25:57 +0000390## -------------------- exponential distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000391
392 def expovariate(self, lambd):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000393 """Exponential distribution.
394
395 lambd is 1.0 divided by the desired mean. (The parameter would be
396 called "lambda", but that is a reserved word in Python.) Returned
397 values range from 0 to positive infinity.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000398
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000399 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000400 # lambd: rate lambd = 1/mean
401 # ('lambda' is a Python reserved word)
402
403 random = self.random
Tim Peters0c9886d2001-01-15 01:18:21 +0000404 u = random()
405 while u <= 1e-7:
406 u = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000407 return -_log(u)/lambd
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000408
Tim Peterscd804102001-01-25 20:25:57 +0000409## -------------------- von Mises distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000410
Tim Petersd7b5e882001-01-25 03:36:26 +0000411 def vonmisesvariate(self, mu, kappa):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000412 """Circular data distribution.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000413
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000414 mu is the mean angle, expressed in radians between 0 and 2*pi, and
415 kappa is the concentration parameter, which must be greater than or
416 equal to zero. If kappa is equal to zero, this distribution reduces
417 to a uniform random angle over the range 0 to 2*pi.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000418
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000419 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000420 # mu: mean angle (in radians between 0 and 2*pi)
421 # kappa: concentration parameter kappa (>= 0)
422 # if kappa = 0 generate uniform random angle
423
424 # Based upon an algorithm published in: Fisher, N.I.,
425 # "Statistical Analysis of Circular Data", Cambridge
426 # University Press, 1993.
427
428 # Thanks to Magnus Kessler for a correction to the
429 # implementation of step 4.
430
431 random = self.random
432 if kappa <= 1e-6:
433 return TWOPI * random()
434
435 a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)
436 b = (a - _sqrt(2.0 * a))/(2.0 * kappa)
437 r = (1.0 + b * b)/(2.0 * b)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000438
Raymond Hettinger42406e62005-04-30 09:02:51 +0000439 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000440 u1 = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000441
442 z = _cos(_pi * u1)
443 f = (1.0 + r * z)/(r + z)
444 c = kappa * (r - f)
445
446 u2 = random()
447
Raymond Hettinger42406e62005-04-30 09:02:51 +0000448 if u2 < c * (2.0 - c) or u2 <= c * _exp(1.0 - c):
Tim Peters0c9886d2001-01-15 01:18:21 +0000449 break
Tim Petersd7b5e882001-01-25 03:36:26 +0000450
451 u3 = random()
452 if u3 > 0.5:
453 theta = (mu % TWOPI) + _acos(f)
454 else:
455 theta = (mu % TWOPI) - _acos(f)
456
457 return theta
458
Tim Peterscd804102001-01-25 20:25:57 +0000459## -------------------- gamma distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000460
461 def gammavariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000462 """Gamma distribution. Not the gamma function!
463
464 Conditions on the parameters are alpha > 0 and beta > 0.
465
466 """
Tim Peters8ac14952002-05-23 15:15:30 +0000467
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000468 # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
Tim Peters8ac14952002-05-23 15:15:30 +0000469
Guido van Rossum570764d2002-05-14 14:08:12 +0000470 # Warning: a few older sources define the gamma distribution in terms
471 # of alpha > -1.0
472 if alpha <= 0.0 or beta <= 0.0:
473 raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
Tim Peters8ac14952002-05-23 15:15:30 +0000474
Tim Petersd7b5e882001-01-25 03:36:26 +0000475 random = self.random
Tim Petersd7b5e882001-01-25 03:36:26 +0000476 if alpha > 1.0:
477
478 # Uses R.C.H. Cheng, "The generation of Gamma
479 # variables with non-integral shape parameters",
480 # Applied Statistics, (1977), 26, No. 1, p71-74
481
Raymond Hettingerca6cdc22002-05-13 23:40:14 +0000482 ainv = _sqrt(2.0 * alpha - 1.0)
483 bbb = alpha - LOG4
484 ccc = alpha + ainv
Tim Peters8ac14952002-05-23 15:15:30 +0000485
Raymond Hettinger42406e62005-04-30 09:02:51 +0000486 while 1:
Tim Petersd7b5e882001-01-25 03:36:26 +0000487 u1 = random()
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000488 if not 1e-7 < u1 < .9999999:
489 continue
490 u2 = 1.0 - random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000491 v = _log(u1/(1.0-u1))/ainv
492 x = alpha*_exp(v)
493 z = u1*u1*u2
494 r = bbb+ccc*v-x
495 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000496 return x * beta
Tim Petersd7b5e882001-01-25 03:36:26 +0000497
498 elif alpha == 1.0:
499 # expovariate(1)
500 u = random()
501 while u <= 1e-7:
502 u = random()
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000503 return -_log(u) * beta
Tim Petersd7b5e882001-01-25 03:36:26 +0000504
505 else: # alpha is between 0 and 1 (exclusive)
506
507 # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
508
Raymond Hettinger42406e62005-04-30 09:02:51 +0000509 while 1:
Tim Petersd7b5e882001-01-25 03:36:26 +0000510 u = random()
511 b = (_e + alpha)/_e
512 p = b*u
513 if p <= 1.0:
Raymond Hettinger42406e62005-04-30 09:02:51 +0000514 x = p ** (1.0/alpha)
Tim Petersd7b5e882001-01-25 03:36:26 +0000515 else:
Tim Petersd7b5e882001-01-25 03:36:26 +0000516 x = -_log((b-p)/alpha)
517 u1 = random()
Raymond Hettinger42406e62005-04-30 09:02:51 +0000518 if p > 1.0:
519 if u1 <= x ** (alpha - 1.0):
520 break
521 elif u1 <= _exp(-x):
Tim Petersd7b5e882001-01-25 03:36:26 +0000522 break
Raymond Hettingerb760efb2002-05-14 06:40:34 +0000523 return x * beta
524
Tim Peterscd804102001-01-25 20:25:57 +0000525## -------------------- Gauss (faster alternative) --------------------
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000526
Tim Petersd7b5e882001-01-25 03:36:26 +0000527 def gauss(self, mu, sigma):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000528 """Gaussian distribution.
529
530 mu is the mean, and sigma is the standard deviation. This is
531 slightly faster than the normalvariate() function.
532
533 Not thread-safe without a lock around calls.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000534
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000535 """
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000536
Tim Petersd7b5e882001-01-25 03:36:26 +0000537 # When x and y are two variables from [0, 1), uniformly
538 # distributed, then
539 #
540 # cos(2*pi*x)*sqrt(-2*log(1-y))
541 # sin(2*pi*x)*sqrt(-2*log(1-y))
542 #
543 # are two *independent* variables with normal distribution
544 # (mu = 0, sigma = 1).
545 # (Lambert Meertens)
546 # (corrected version; bug discovered by Mike Miller, fixed by LM)
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000547
Tim Petersd7b5e882001-01-25 03:36:26 +0000548 # Multithreading note: When two threads call this function
549 # simultaneously, it is possible that they will receive the
550 # same return value. The window is very small though. To
551 # avoid this, you have to use a lock around all calls. (I
552 # didn't want to slow this down in the serial case by using a
553 # lock here.)
Guido van Rossumd03e1191998-05-29 17:51:31 +0000554
Tim Petersd7b5e882001-01-25 03:36:26 +0000555 random = self.random
556 z = self.gauss_next
557 self.gauss_next = None
558 if z is None:
559 x2pi = random() * TWOPI
560 g2rad = _sqrt(-2.0 * _log(1.0 - random()))
561 z = _cos(x2pi) * g2rad
562 self.gauss_next = _sin(x2pi) * g2rad
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000563
Tim Petersd7b5e882001-01-25 03:36:26 +0000564 return mu + z*sigma
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000565
Tim Peterscd804102001-01-25 20:25:57 +0000566## -------------------- beta --------------------
Tim Peters85e2e472001-01-26 06:49:56 +0000567## See
568## http://sourceforge.net/bugs/?func=detailbug&bug_id=130030&group_id=5470
569## for Ivan Frohne's insightful analysis of why the original implementation:
570##
571## def betavariate(self, alpha, beta):
572## # Discrete Event Simulation in C, pp 87-88.
573##
574## y = self.expovariate(alpha)
575## z = self.expovariate(1.0/beta)
576## return z/(y+z)
577##
578## was dead wrong, and how it probably got that way.
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000579
Tim Petersd7b5e882001-01-25 03:36:26 +0000580 def betavariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000581 """Beta distribution.
582
Raymond Hettinger1b0ce852007-01-19 18:07:18 +0000583 Conditions on the parameters are alpha > 0 and beta > 0.
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000584 Returned values range between 0 and 1.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000585
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000586 """
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000587
Tim Peters85e2e472001-01-26 06:49:56 +0000588 # This version due to Janne Sinkkonen, and matches all the std
589 # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
590 y = self.gammavariate(alpha, 1.)
591 if y == 0:
592 return 0.0
593 else:
594 return y / (y + self.gammavariate(beta, 1.))
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000595
Tim Peterscd804102001-01-25 20:25:57 +0000596## -------------------- Pareto --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000597
Tim Petersd7b5e882001-01-25 03:36:26 +0000598 def paretovariate(self, alpha):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000599 """Pareto distribution. alpha is the shape parameter."""
Tim Petersd7b5e882001-01-25 03:36:26 +0000600 # Jain, pg. 495
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000601
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000602 u = 1.0 - self.random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000603 return 1.0 / pow(u, 1.0/alpha)
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000604
Tim Peterscd804102001-01-25 20:25:57 +0000605## -------------------- Weibull --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000606
Tim Petersd7b5e882001-01-25 03:36:26 +0000607 def weibullvariate(self, alpha, beta):
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000608 """Weibull distribution.
609
610 alpha is the scale parameter and beta is the shape parameter.
Raymond Hettingeref4d4bd2002-05-23 23:58:17 +0000611
Raymond Hettingerc32f0332002-05-23 19:44:49 +0000612 """
Tim Petersd7b5e882001-01-25 03:36:26 +0000613 # Jain, pg. 499; bug fix courtesy Bill Arms
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000614
Raymond Hettinger73ced7e2003-01-04 09:26:32 +0000615 u = 1.0 - self.random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000616 return alpha * pow(-_log(u), 1.0/beta)
Guido van Rossum6c395ba1999-08-18 13:53:28 +0000617
Raymond Hettinger40f62172002-12-29 23:03:38 +0000618## -------------------- Wichmann-Hill -------------------
619
620class WichmannHill(Random):
621
622 VERSION = 1 # used by getstate/setstate
623
624 def seed(self, a=None):
625 """Initialize internal state from hashable object.
626
Raymond Hettinger23f12412004-09-13 22:23:21 +0000627 None or no argument seeds from current time or from an operating
628 system specific randomness source if available.
Raymond Hettinger40f62172002-12-29 23:03:38 +0000629
630 If a is not None or an int or long, hash(a) is used instead.
631
632 If a is an int or long, a is used directly. Distinct values between
633 0 and 27814431486575L inclusive are guaranteed to yield distinct
634 internal states (this guarantee is specific to the default
635 Wichmann-Hill generator).
636 """
637
638 if a is None:
Raymond Hettingerc1c43ca2004-09-05 00:00:42 +0000639 try:
640 a = long(_hexlify(_urandom(16)), 16)
641 except NotImplementedError:
Raymond Hettinger356a4592004-08-30 06:14:31 +0000642 import time
643 a = long(time.time() * 256) # use fractional seconds
Raymond Hettinger40f62172002-12-29 23:03:38 +0000644
645 if not isinstance(a, (int, long)):
646 a = hash(a)
647
648 a, x = divmod(a, 30268)
649 a, y = divmod(a, 30306)
650 a, z = divmod(a, 30322)
651 self._seed = int(x)+1, int(y)+1, int(z)+1
652
653 self.gauss_next = None
654
655 def random(self):
656 """Get the next random number in the range [0.0, 1.0)."""
657
658 # Wichman-Hill random number generator.
659 #
660 # Wichmann, B. A. & Hill, I. D. (1982)
661 # Algorithm AS 183:
662 # An efficient and portable pseudo-random number generator
663 # Applied Statistics 31 (1982) 188-190
664 #
665 # see also:
666 # Correction to Algorithm AS 183
667 # Applied Statistics 33 (1984) 123
668 #
669 # McLeod, A. I. (1985)
670 # A remark on Algorithm AS 183
671 # Applied Statistics 34 (1985),198-200
672
673 # This part is thread-unsafe:
674 # BEGIN CRITICAL SECTION
675 x, y, z = self._seed
676 x = (171 * x) % 30269
677 y = (172 * y) % 30307
678 z = (170 * z) % 30323
679 self._seed = x, y, z
680 # END CRITICAL SECTION
681
682 # Note: on a platform using IEEE-754 double arithmetic, this can
683 # never return 0.0 (asserted by Tim; proof too long for a comment).
684 return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
685
686 def getstate(self):
687 """Return internal state; can be passed to setstate() later."""
688 return self.VERSION, self._seed, self.gauss_next
689
690 def setstate(self, state):
691 """Restore internal state from object returned by getstate()."""
692 version = state[0]
693 if version == 1:
694 version, self._seed, self.gauss_next = state
695 else:
696 raise ValueError("state with version %s passed to "
697 "Random.setstate() of version %s" %
698 (version, self.VERSION))
699
700 def jumpahead(self, n):
701 """Act as if n calls to random() were made, but quickly.
702
703 n is an int, greater than or equal to 0.
704
705 Example use: If you have 2 threads and know that each will
706 consume no more than a million random numbers, create two Random
707 objects r1 and r2, then do
708 r2.setstate(r1.getstate())
709 r2.jumpahead(1000000)
710 Then r1 and r2 will use guaranteed-disjoint segments of the full
711 period.
712 """
713
714 if not n >= 0:
715 raise ValueError("n must be >= 0")
716 x, y, z = self._seed
717 x = int(x * pow(171, n, 30269)) % 30269
718 y = int(y * pow(172, n, 30307)) % 30307
719 z = int(z * pow(170, n, 30323)) % 30323
720 self._seed = x, y, z
721
722 def __whseed(self, x=0, y=0, z=0):
723 """Set the Wichmann-Hill seed from (x, y, z).
724
725 These must be integers in the range [0, 256).
726 """
727
728 if not type(x) == type(y) == type(z) == int:
729 raise TypeError('seeds must be integers')
730 if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256):
731 raise ValueError('seeds must be in range(0, 256)')
732 if 0 == x == y == z:
733 # Initialize from current time
734 import time
735 t = long(time.time() * 256)
736 t = int((t&0xffffff) ^ (t>>24))
737 t, x = divmod(t, 256)
738 t, y = divmod(t, 256)
739 t, z = divmod(t, 256)
740 # Zero is a poor seed, so substitute 1
741 self._seed = (x or 1, y or 1, z or 1)
742
743 self.gauss_next = None
744
745 def whseed(self, a=None):
746 """Seed from hashable object's hash code.
747
748 None or no argument seeds from current time. It is not guaranteed
749 that objects with distinct hash codes lead to distinct internal
750 states.
751
752 This is obsolete, provided for compatibility with the seed routine
753 used prior to Python 2.1. Use the .seed() method instead.
754 """
755
756 if a is None:
757 self.__whseed()
758 return
759 a = hash(a)
760 a, x = divmod(a, 256)
761 a, y = divmod(a, 256)
762 a, z = divmod(a, 256)
763 x = (x + a) % 256 or 1
764 y = (y + a) % 256 or 1
765 z = (z + a) % 256 or 1
766 self.__whseed(x, y, z)
767
Raymond Hettinger23f12412004-09-13 22:23:21 +0000768## --------------- Operating System Random Source ------------------
Raymond Hettinger356a4592004-08-30 06:14:31 +0000769
Raymond Hettinger23f12412004-09-13 22:23:21 +0000770class SystemRandom(Random):
771 """Alternate random number generator using sources provided
772 by the operating system (such as /dev/urandom on Unix or
773 CryptGenRandom on Windows).
Raymond Hettinger356a4592004-08-30 06:14:31 +0000774
775 Not available on all systems (see os.urandom() for details).
776 """
777
778 def random(self):
779 """Get the next random number in the range [0.0, 1.0)."""
Tim Peters7c2a85b2004-08-31 02:19:55 +0000780 return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Raymond Hettinger356a4592004-08-30 06:14:31 +0000781
782 def getrandbits(self, k):
783 """getrandbits(k) -> x. Generates a long int with k random bits."""
Raymond Hettinger356a4592004-08-30 06:14:31 +0000784 if k <= 0:
785 raise ValueError('number of bits must be greater than zero')
786 if k != int(k):
787 raise TypeError('number of bits should be an integer')
788 bytes = (k + 7) // 8 # bits / 8 and rounded up
789 x = long(_hexlify(_urandom(bytes)), 16)
790 return x >> (bytes * 8 - k) # trim excess bits
791
792 def _stub(self, *args, **kwds):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000793 "Stub method. Not used for a system random number generator."
Raymond Hettinger356a4592004-08-30 06:14:31 +0000794 return None
795 seed = jumpahead = _stub
796
797 def _notimplemented(self, *args, **kwds):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000798 "Method should not be called for a system random number generator."
799 raise NotImplementedError('System entropy source does not have state.')
Raymond Hettinger356a4592004-08-30 06:14:31 +0000800 getstate = setstate = _notimplemented
801
Tim Peterscd804102001-01-25 20:25:57 +0000802## -------------------- test program --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000803
Raymond Hettinger62297132003-08-30 01:24:19 +0000804def _test_generator(n, func, args):
Tim Peters0c9886d2001-01-15 01:18:21 +0000805 import time
Raymond Hettinger62297132003-08-30 01:24:19 +0000806 print n, 'times', func.__name__
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000807 total = 0.0
Tim Peters0c9886d2001-01-15 01:18:21 +0000808 sqsum = 0.0
809 smallest = 1e10
810 largest = -1e10
811 t0 = time.time()
812 for i in range(n):
Raymond Hettinger62297132003-08-30 01:24:19 +0000813 x = func(*args)
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000814 total += x
Tim Peters0c9886d2001-01-15 01:18:21 +0000815 sqsum = sqsum + x*x
816 smallest = min(x, smallest)
817 largest = max(x, largest)
818 t1 = time.time()
819 print round(t1-t0, 3), 'sec,',
Raymond Hettingerb98154e2003-05-24 17:26:02 +0000820 avg = total/n
Tim Petersd7b5e882001-01-25 03:36:26 +0000821 stddev = _sqrt(sqsum/n - avg*avg)
Tim Peters0c9886d2001-01-15 01:18:21 +0000822 print 'avg %g, stddev %g, min %g, max %g' % \
823 (avg, stddev, smallest, largest)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000824
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000825
826def _test(N=2000):
Raymond Hettinger62297132003-08-30 01:24:19 +0000827 _test_generator(N, random, ())
828 _test_generator(N, normalvariate, (0.0, 1.0))
829 _test_generator(N, lognormvariate, (0.0, 1.0))
830 _test_generator(N, vonmisesvariate, (0.0, 1.0))
831 _test_generator(N, gammavariate, (0.01, 1.0))
832 _test_generator(N, gammavariate, (0.1, 1.0))
833 _test_generator(N, gammavariate, (0.1, 2.0))
834 _test_generator(N, gammavariate, (0.5, 1.0))
835 _test_generator(N, gammavariate, (0.9, 1.0))
836 _test_generator(N, gammavariate, (1.0, 1.0))
837 _test_generator(N, gammavariate, (2.0, 1.0))
838 _test_generator(N, gammavariate, (20.0, 1.0))
839 _test_generator(N, gammavariate, (200.0, 1.0))
840 _test_generator(N, gauss, (0.0, 1.0))
841 _test_generator(N, betavariate, (3.0, 3.0))
Tim Peterscd804102001-01-25 20:25:57 +0000842
Tim Peters715c4c42001-01-26 22:56:56 +0000843# Create one instance, seeded from current time, and export its methods
Raymond Hettinger40f62172002-12-29 23:03:38 +0000844# as module-level functions. The functions share state across all uses
845#(both in the user's code and in the Python libraries), but that's fine
846# for most programs and is easier for the casual user than making them
847# instantiate their own Random() instance.
848
Tim Petersd7b5e882001-01-25 03:36:26 +0000849_inst = Random()
850seed = _inst.seed
851random = _inst.random
852uniform = _inst.uniform
853randint = _inst.randint
854choice = _inst.choice
855randrange = _inst.randrange
Raymond Hettingerf24eb352002-11-12 17:41:57 +0000856sample = _inst.sample
Tim Petersd7b5e882001-01-25 03:36:26 +0000857shuffle = _inst.shuffle
858normalvariate = _inst.normalvariate
859lognormvariate = _inst.lognormvariate
Tim Petersd7b5e882001-01-25 03:36:26 +0000860expovariate = _inst.expovariate
861vonmisesvariate = _inst.vonmisesvariate
862gammavariate = _inst.gammavariate
Tim Petersd7b5e882001-01-25 03:36:26 +0000863gauss = _inst.gauss
864betavariate = _inst.betavariate
865paretovariate = _inst.paretovariate
866weibullvariate = _inst.weibullvariate
867getstate = _inst.getstate
868setstate = _inst.setstate
Tim Petersd52269b2001-01-25 06:23:18 +0000869jumpahead = _inst.jumpahead
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000870getrandbits = _inst.getrandbits
Tim Petersd7b5e882001-01-25 03:36:26 +0000871
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000872if __name__ == '__main__':
Tim Petersd7b5e882001-01-25 03:36:26 +0000873 _test()