]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.2/Lib/random.py
EmbeddedPkg: Extend NvVarStoreFormattedLib LIBRARY_CLASS
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.2 / Lib / random.py
CommitLineData
4710c53d 1"""Random variable generators.\r
2\r
3 integers\r
4 --------\r
5 uniform within range\r
6\r
7 sequences\r
8 ---------\r
9 pick random element\r
10 pick random sample\r
11 generate random permutation\r
12\r
13 distributions on the real line:\r
14 ------------------------------\r
15 uniform\r
16 triangular\r
17 normal (Gaussian)\r
18 lognormal\r
19 negative exponential\r
20 gamma\r
21 beta\r
22 pareto\r
23 Weibull\r
24\r
25 distributions on the circle (angles 0 to 2pi)\r
26 ---------------------------------------------\r
27 circular uniform\r
28 von Mises\r
29\r
30General notes on the underlying Mersenne Twister core generator:\r
31\r
32* The period is 2**19937-1.\r
33* It is one of the most extensively tested generators in existence.\r
34* Without a direct way to compute N steps forward, the semantics of\r
35 jumpahead(n) are weakened to simply jump to another distant state and rely\r
36 on the large period to avoid overlapping sequences.\r
37* The random() method is implemented in C, executes in a single Python step,\r
38 and is, therefore, threadsafe.\r
39\r
40"""\r
41\r
42from __future__ import division\r
43from warnings import warn as _warn\r
44from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType\r
45from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil\r
46from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin\r
47from os import urandom as _urandom\r
48from binascii import hexlify as _hexlify\r
49import hashlib as _hashlib\r
50\r
51__all__ = ["Random","seed","random","uniform","randint","choice","sample",\r
52 "randrange","shuffle","normalvariate","lognormvariate",\r
53 "expovariate","vonmisesvariate","gammavariate","triangular",\r
54 "gauss","betavariate","paretovariate","weibullvariate",\r
55 "getstate","setstate","jumpahead", "WichmannHill", "getrandbits",\r
56 "SystemRandom"]\r
57\r
58NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)\r
59TWOPI = 2.0*_pi\r
60LOG4 = _log(4.0)\r
61SG_MAGICCONST = 1.0 + _log(4.5)\r
62BPF = 53 # Number of bits in a float\r
63RECIP_BPF = 2**-BPF\r
64\r
65\r
66# Translated by Guido van Rossum from C source provided by\r
67# Adrian Baddeley. Adapted by Raymond Hettinger for use with\r
68# the Mersenne Twister and os.urandom() core generators.\r
69\r
70import _random\r
71\r
72class Random(_random.Random):\r
73 """Random number generator base class used by bound module functions.\r
74\r
75 Used to instantiate instances of Random to get generators that don't\r
76 share state. Especially useful for multi-threaded programs, creating\r
77 a different instance of Random for each thread, and using the jumpahead()\r
78 method to ensure that the generated sequences seen by each thread don't\r
79 overlap.\r
80\r
81 Class Random can also be subclassed if you want to use a different basic\r
82 generator of your own devising: in that case, override the following\r
83 methods: random(), seed(), getstate(), setstate() and jumpahead().\r
84 Optionally, implement a getrandbits() method so that randrange() can cover\r
85 arbitrarily large ranges.\r
86\r
87 """\r
88\r
89 VERSION = 3 # used by getstate/setstate\r
90\r
91 def __init__(self, x=None):\r
92 """Initialize an instance.\r
93\r
94 Optional argument x controls seeding, as for Random.seed().\r
95 """\r
96\r
97 self.seed(x)\r
98 self.gauss_next = None\r
99\r
100 def seed(self, a=None):\r
101 """Initialize internal state from hashable object.\r
102\r
103 None or no argument seeds from current time or from an operating\r
104 system specific randomness source if available.\r
105\r
106 If a is not None or an int or long, hash(a) is used instead.\r
107 """\r
108\r
109 if a is None:\r
110 try:\r
111 a = long(_hexlify(_urandom(16)), 16)\r
112 except NotImplementedError:\r
113 import time\r
114 a = long(time.time() * 256) # use fractional seconds\r
115\r
116 super(Random, self).seed(a)\r
117 self.gauss_next = None\r
118\r
119 def getstate(self):\r
120 """Return internal state; can be passed to setstate() later."""\r
121 return self.VERSION, super(Random, self).getstate(), self.gauss_next\r
122\r
123 def setstate(self, state):\r
124 """Restore internal state from object returned by getstate()."""\r
125 version = state[0]\r
126 if version == 3:\r
127 version, internalstate, self.gauss_next = state\r
128 super(Random, self).setstate(internalstate)\r
129 elif version == 2:\r
130 version, internalstate, self.gauss_next = state\r
131 # In version 2, the state was saved as signed ints, which causes\r
132 # inconsistencies between 32/64-bit systems. The state is\r
133 # really unsigned 32-bit ints, so we convert negative ints from\r
134 # version 2 to positive longs for version 3.\r
135 try:\r
136 internalstate = tuple( long(x) % (2**32) for x in internalstate )\r
137 except ValueError, e:\r
138 raise TypeError, e\r
139 super(Random, self).setstate(internalstate)\r
140 else:\r
141 raise ValueError("state with version %s passed to "\r
142 "Random.setstate() of version %s" %\r
143 (version, self.VERSION))\r
144\r
145 def jumpahead(self, n):\r
146 """Change the internal state to one that is likely far away\r
147 from the current state. This method will not be in Py3.x,\r
148 so it is better to simply reseed.\r
149 """\r
150 # The super.jumpahead() method uses shuffling to change state,\r
151 # so it needs a large and "interesting" n to work with. Here,\r
152 # we use hashing to create a large n for the shuffle.\r
153 s = repr(n) + repr(self.getstate())\r
154 n = int(_hashlib.new('sha512', s).hexdigest(), 16)\r
155 super(Random, self).jumpahead(n)\r
156\r
157## ---- Methods below this point do not need to be overridden when\r
158## ---- subclassing for the purpose of using a different core generator.\r
159\r
160## -------------------- pickle support -------------------\r
161\r
162 def __getstate__(self): # for pickle\r
163 return self.getstate()\r
164\r
165 def __setstate__(self, state): # for pickle\r
166 self.setstate(state)\r
167\r
168 def __reduce__(self):\r
169 return self.__class__, (), self.getstate()\r
170\r
171## -------------------- integer methods -------------------\r
172\r
173 def randrange(self, start, stop=None, step=1, int=int, default=None,\r
174 maxwidth=1L<<BPF):\r
175 """Choose a random item from range(start, stop[, step]).\r
176\r
177 This fixes the problem with randint() which includes the\r
178 endpoint; in Python this is usually not what you want.\r
179 Do not supply the 'int', 'default', and 'maxwidth' arguments.\r
180 """\r
181\r
182 # This code is a bit messy to make it fast for the\r
183 # common case while still doing adequate error checking.\r
184 istart = int(start)\r
185 if istart != start:\r
186 raise ValueError, "non-integer arg 1 for randrange()"\r
187 if stop is default:\r
188 if istart > 0:\r
189 if istart >= maxwidth:\r
190 return self._randbelow(istart)\r
191 return int(self.random() * istart)\r
192 raise ValueError, "empty range for randrange()"\r
193\r
194 # stop argument supplied.\r
195 istop = int(stop)\r
196 if istop != stop:\r
197 raise ValueError, "non-integer stop for randrange()"\r
198 width = istop - istart\r
199 if step == 1 and width > 0:\r
200 # Note that\r
201 # int(istart + self.random()*width)\r
202 # instead would be incorrect. For example, consider istart\r
203 # = -2 and istop = 0. Then the guts would be in\r
204 # -2.0 to 0.0 exclusive on both ends (ignoring that random()\r
205 # might return 0.0), and because int() truncates toward 0, the\r
206 # final result would be -1 or 0 (instead of -2 or -1).\r
207 # istart + int(self.random()*width)\r
208 # would also be incorrect, for a subtler reason: the RHS\r
209 # can return a long, and then randrange() would also return\r
210 # a long, but we're supposed to return an int (for backward\r
211 # compatibility).\r
212\r
213 if width >= maxwidth:\r
214 return int(istart + self._randbelow(width))\r
215 return int(istart + int(self.random()*width))\r
216 if step == 1:\r
217 raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)\r
218\r
219 # Non-unit step argument supplied.\r
220 istep = int(step)\r
221 if istep != step:\r
222 raise ValueError, "non-integer step for randrange()"\r
223 if istep > 0:\r
224 n = (width + istep - 1) // istep\r
225 elif istep < 0:\r
226 n = (width + istep + 1) // istep\r
227 else:\r
228 raise ValueError, "zero step for randrange()"\r
229\r
230 if n <= 0:\r
231 raise ValueError, "empty range for randrange()"\r
232\r
233 if n >= maxwidth:\r
234 return istart + istep*self._randbelow(n)\r
235 return istart + istep*int(self.random() * n)\r
236\r
237 def randint(self, a, b):\r
238 """Return random integer in range [a, b], including both end points.\r
239 """\r
240\r
241 return self.randrange(a, b+1)\r
242\r
243 def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L<<BPF,\r
244 _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):\r
245 """Return a random int in the range [0,n)\r
246\r
247 Handles the case where n has more bits than returned\r
248 by a single call to the underlying generator.\r
249 """\r
250\r
251 try:\r
252 getrandbits = self.getrandbits\r
253 except AttributeError:\r
254 pass\r
255 else:\r
256 # Only call self.getrandbits if the original random() builtin method\r
257 # has not been overridden or if a new getrandbits() was supplied.\r
258 # This assures that the two methods correspond.\r
259 if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:\r
260 k = int(1.00001 + _log(n-1, 2.0)) # 2**k > n-1 > 2**(k-2)\r
261 r = getrandbits(k)\r
262 while r >= n:\r
263 r = getrandbits(k)\r
264 return r\r
265 if n >= _maxwidth:\r
266 _warn("Underlying random() generator does not supply \n"\r
267 "enough bits to choose from a population range this large")\r
268 return int(self.random() * n)\r
269\r
270## -------------------- sequence methods -------------------\r
271\r
272 def choice(self, seq):\r
273 """Choose a random element from a non-empty sequence."""\r
274 return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty\r
275\r
276 def shuffle(self, x, random=None, int=int):\r
277 """x, random=random.random -> shuffle list x in place; return None.\r
278\r
279 Optional arg random is a 0-argument function returning a random\r
280 float in [0.0, 1.0); by default, the standard random.random.\r
281 """\r
282\r
283 if random is None:\r
284 random = self.random\r
285 for i in reversed(xrange(1, len(x))):\r
286 # pick an element in x[:i+1] with which to exchange x[i]\r
287 j = int(random() * (i+1))\r
288 x[i], x[j] = x[j], x[i]\r
289\r
290 def sample(self, population, k):\r
291 """Chooses k unique random elements from a population sequence.\r
292\r
293 Returns a new list containing elements from the population while\r
294 leaving the original population unchanged. The resulting list is\r
295 in selection order so that all sub-slices will also be valid random\r
296 samples. This allows raffle winners (the sample) to be partitioned\r
297 into grand prize and second place winners (the subslices).\r
298\r
299 Members of the population need not be hashable or unique. If the\r
300 population contains repeats, then each occurrence is a possible\r
301 selection in the sample.\r
302\r
303 To choose a sample in a range of integers, use xrange as an argument.\r
304 This is especially fast and space efficient for sampling from a\r
305 large population: sample(xrange(10000000), 60)\r
306 """\r
307\r
308 # Sampling without replacement entails tracking either potential\r
309 # selections (the pool) in a list or previous selections in a set.\r
310\r
311 # When the number of selections is small compared to the\r
312 # population, then tracking selections is efficient, requiring\r
313 # only a small set and an occasional reselection. For\r
314 # a larger number of selections, the pool tracking method is\r
315 # preferred since the list takes less space than the\r
316 # set and it doesn't suffer from frequent reselections.\r
317\r
318 n = len(population)\r
319 if not 0 <= k <= n:\r
320 raise ValueError("sample larger than population")\r
321 random = self.random\r
322 _int = int\r
323 result = [None] * k\r
324 setsize = 21 # size of a small set minus size of an empty list\r
325 if k > 5:\r
326 setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets\r
327 if n <= setsize or hasattr(population, "keys"):\r
328 # An n-length list is smaller than a k-length set, or this is a\r
329 # mapping type so the other algorithm wouldn't work.\r
330 pool = list(population)\r
331 for i in xrange(k): # invariant: non-selected at [0,n-i)\r
332 j = _int(random() * (n-i))\r
333 result[i] = pool[j]\r
334 pool[j] = pool[n-i-1] # move non-selected item into vacancy\r
335 else:\r
336 try:\r
337 selected = set()\r
338 selected_add = selected.add\r
339 for i in xrange(k):\r
340 j = _int(random() * n)\r
341 while j in selected:\r
342 j = _int(random() * n)\r
343 selected_add(j)\r
344 result[i] = population[j]\r
345 except (TypeError, KeyError): # handle (at least) sets\r
346 if isinstance(population, list):\r
347 raise\r
348 return self.sample(tuple(population), k)\r
349 return result\r
350\r
351## -------------------- real-valued distributions -------------------\r
352\r
353## -------------------- uniform distribution -------------------\r
354\r
355 def uniform(self, a, b):\r
356 "Get a random number in the range [a, b) or [a, b] depending on rounding."\r
357 return a + (b-a) * self.random()\r
358\r
359## -------------------- triangular --------------------\r
360\r
361 def triangular(self, low=0.0, high=1.0, mode=None):\r
362 """Triangular distribution.\r
363\r
364 Continuous distribution bounded by given lower and upper limits,\r
365 and having a given mode value in-between.\r
366\r
367 http://en.wikipedia.org/wiki/Triangular_distribution\r
368\r
369 """\r
370 u = self.random()\r
371 c = 0.5 if mode is None else (mode - low) / (high - low)\r
372 if u > c:\r
373 u = 1.0 - u\r
374 c = 1.0 - c\r
375 low, high = high, low\r
376 return low + (high - low) * (u * c) ** 0.5\r
377\r
378## -------------------- normal distribution --------------------\r
379\r
380 def normalvariate(self, mu, sigma):\r
381 """Normal distribution.\r
382\r
383 mu is the mean, and sigma is the standard deviation.\r
384\r
385 """\r
386 # mu = mean, sigma = standard deviation\r
387\r
388 # Uses Kinderman and Monahan method. Reference: Kinderman,\r
389 # A.J. and Monahan, J.F., "Computer generation of random\r
390 # variables using the ratio of uniform deviates", ACM Trans\r
391 # Math Software, 3, (1977), pp257-260.\r
392\r
393 random = self.random\r
394 while 1:\r
395 u1 = random()\r
396 u2 = 1.0 - random()\r
397 z = NV_MAGICCONST*(u1-0.5)/u2\r
398 zz = z*z/4.0\r
399 if zz <= -_log(u2):\r
400 break\r
401 return mu + z*sigma\r
402\r
403## -------------------- lognormal distribution --------------------\r
404\r
405 def lognormvariate(self, mu, sigma):\r
406 """Log normal distribution.\r
407\r
408 If you take the natural logarithm of this distribution, you'll get a\r
409 normal distribution with mean mu and standard deviation sigma.\r
410 mu can have any value, and sigma must be greater than zero.\r
411\r
412 """\r
413 return _exp(self.normalvariate(mu, sigma))\r
414\r
415## -------------------- exponential distribution --------------------\r
416\r
417 def expovariate(self, lambd):\r
418 """Exponential distribution.\r
419\r
420 lambd is 1.0 divided by the desired mean. It should be\r
421 nonzero. (The parameter would be called "lambda", but that is\r
422 a reserved word in Python.) Returned values range from 0 to\r
423 positive infinity if lambd is positive, and from negative\r
424 infinity to 0 if lambd is negative.\r
425\r
426 """\r
427 # lambd: rate lambd = 1/mean\r
428 # ('lambda' is a Python reserved word)\r
429\r
430 random = self.random\r
431 u = random()\r
432 while u <= 1e-7:\r
433 u = random()\r
434 return -_log(u)/lambd\r
435\r
436## -------------------- von Mises distribution --------------------\r
437\r
438 def vonmisesvariate(self, mu, kappa):\r
439 """Circular data distribution.\r
440\r
441 mu is the mean angle, expressed in radians between 0 and 2*pi, and\r
442 kappa is the concentration parameter, which must be greater than or\r
443 equal to zero. If kappa is equal to zero, this distribution reduces\r
444 to a uniform random angle over the range 0 to 2*pi.\r
445\r
446 """\r
447 # mu: mean angle (in radians between 0 and 2*pi)\r
448 # kappa: concentration parameter kappa (>= 0)\r
449 # if kappa = 0 generate uniform random angle\r
450\r
451 # Based upon an algorithm published in: Fisher, N.I.,\r
452 # "Statistical Analysis of Circular Data", Cambridge\r
453 # University Press, 1993.\r
454\r
455 # Thanks to Magnus Kessler for a correction to the\r
456 # implementation of step 4.\r
457\r
458 random = self.random\r
459 if kappa <= 1e-6:\r
460 return TWOPI * random()\r
461\r
462 a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)\r
463 b = (a - _sqrt(2.0 * a))/(2.0 * kappa)\r
464 r = (1.0 + b * b)/(2.0 * b)\r
465\r
466 while 1:\r
467 u1 = random()\r
468\r
469 z = _cos(_pi * u1)\r
470 f = (1.0 + r * z)/(r + z)\r
471 c = kappa * (r - f)\r
472\r
473 u2 = random()\r
474\r
475 if u2 < c * (2.0 - c) or u2 <= c * _exp(1.0 - c):\r
476 break\r
477\r
478 u3 = random()\r
479 if u3 > 0.5:\r
480 theta = (mu % TWOPI) + _acos(f)\r
481 else:\r
482 theta = (mu % TWOPI) - _acos(f)\r
483\r
484 return theta\r
485\r
486## -------------------- gamma distribution --------------------\r
487\r
488 def gammavariate(self, alpha, beta):\r
489 """Gamma distribution. Not the gamma function!\r
490\r
491 Conditions on the parameters are alpha > 0 and beta > 0.\r
492\r
493 The probability distribution function is:\r
494\r
495 x ** (alpha - 1) * math.exp(-x / beta)\r
496 pdf(x) = --------------------------------------\r
497 math.gamma(alpha) * beta ** alpha\r
498\r
499 """\r
500\r
501 # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2\r
502\r
503 # Warning: a few older sources define the gamma distribution in terms\r
504 # of alpha > -1.0\r
505 if alpha <= 0.0 or beta <= 0.0:\r
506 raise ValueError, 'gammavariate: alpha and beta must be > 0.0'\r
507\r
508 random = self.random\r
509 if alpha > 1.0:\r
510\r
511 # Uses R.C.H. Cheng, "The generation of Gamma\r
512 # variables with non-integral shape parameters",\r
513 # Applied Statistics, (1977), 26, No. 1, p71-74\r
514\r
515 ainv = _sqrt(2.0 * alpha - 1.0)\r
516 bbb = alpha - LOG4\r
517 ccc = alpha + ainv\r
518\r
519 while 1:\r
520 u1 = random()\r
521 if not 1e-7 < u1 < .9999999:\r
522 continue\r
523 u2 = 1.0 - random()\r
524 v = _log(u1/(1.0-u1))/ainv\r
525 x = alpha*_exp(v)\r
526 z = u1*u1*u2\r
527 r = bbb+ccc*v-x\r
528 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):\r
529 return x * beta\r
530\r
531 elif alpha == 1.0:\r
532 # expovariate(1)\r
533 u = random()\r
534 while u <= 1e-7:\r
535 u = random()\r
536 return -_log(u) * beta\r
537\r
538 else: # alpha is between 0 and 1 (exclusive)\r
539\r
540 # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle\r
541\r
542 while 1:\r
543 u = random()\r
544 b = (_e + alpha)/_e\r
545 p = b*u\r
546 if p <= 1.0:\r
547 x = p ** (1.0/alpha)\r
548 else:\r
549 x = -_log((b-p)/alpha)\r
550 u1 = random()\r
551 if p > 1.0:\r
552 if u1 <= x ** (alpha - 1.0):\r
553 break\r
554 elif u1 <= _exp(-x):\r
555 break\r
556 return x * beta\r
557\r
558## -------------------- Gauss (faster alternative) --------------------\r
559\r
560 def gauss(self, mu, sigma):\r
561 """Gaussian distribution.\r
562\r
563 mu is the mean, and sigma is the standard deviation. This is\r
564 slightly faster than the normalvariate() function.\r
565\r
566 Not thread-safe without a lock around calls.\r
567\r
568 """\r
569\r
570 # When x and y are two variables from [0, 1), uniformly\r
571 # distributed, then\r
572 #\r
573 # cos(2*pi*x)*sqrt(-2*log(1-y))\r
574 # sin(2*pi*x)*sqrt(-2*log(1-y))\r
575 #\r
576 # are two *independent* variables with normal distribution\r
577 # (mu = 0, sigma = 1).\r
578 # (Lambert Meertens)\r
579 # (corrected version; bug discovered by Mike Miller, fixed by LM)\r
580\r
581 # Multithreading note: When two threads call this function\r
582 # simultaneously, it is possible that they will receive the\r
583 # same return value. The window is very small though. To\r
584 # avoid this, you have to use a lock around all calls. (I\r
585 # didn't want to slow this down in the serial case by using a\r
586 # lock here.)\r
587\r
588 random = self.random\r
589 z = self.gauss_next\r
590 self.gauss_next = None\r
591 if z is None:\r
592 x2pi = random() * TWOPI\r
593 g2rad = _sqrt(-2.0 * _log(1.0 - random()))\r
594 z = _cos(x2pi) * g2rad\r
595 self.gauss_next = _sin(x2pi) * g2rad\r
596\r
597 return mu + z*sigma\r
598\r
599## -------------------- beta --------------------\r
600## See\r
601## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html\r
602## for Ivan Frohne's insightful analysis of why the original implementation:\r
603##\r
604## def betavariate(self, alpha, beta):\r
605## # Discrete Event Simulation in C, pp 87-88.\r
606##\r
607## y = self.expovariate(alpha)\r
608## z = self.expovariate(1.0/beta)\r
609## return z/(y+z)\r
610##\r
611## was dead wrong, and how it probably got that way.\r
612\r
613 def betavariate(self, alpha, beta):\r
614 """Beta distribution.\r
615\r
616 Conditions on the parameters are alpha > 0 and beta > 0.\r
617 Returned values range between 0 and 1.\r
618\r
619 """\r
620\r
621 # This version due to Janne Sinkkonen, and matches all the std\r
622 # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").\r
623 y = self.gammavariate(alpha, 1.)\r
624 if y == 0:\r
625 return 0.0\r
626 else:\r
627 return y / (y + self.gammavariate(beta, 1.))\r
628\r
629## -------------------- Pareto --------------------\r
630\r
631 def paretovariate(self, alpha):\r
632 """Pareto distribution. alpha is the shape parameter."""\r
633 # Jain, pg. 495\r
634\r
635 u = 1.0 - self.random()\r
636 return 1.0 / pow(u, 1.0/alpha)\r
637\r
638## -------------------- Weibull --------------------\r
639\r
640 def weibullvariate(self, alpha, beta):\r
641 """Weibull distribution.\r
642\r
643 alpha is the scale parameter and beta is the shape parameter.\r
644\r
645 """\r
646 # Jain, pg. 499; bug fix courtesy Bill Arms\r
647\r
648 u = 1.0 - self.random()\r
649 return alpha * pow(-_log(u), 1.0/beta)\r
650\r
651## -------------------- Wichmann-Hill -------------------\r
652\r
653class WichmannHill(Random):\r
654\r
655 VERSION = 1 # used by getstate/setstate\r
656\r
657 def seed(self, a=None):\r
658 """Initialize internal state from hashable object.\r
659\r
660 None or no argument seeds from current time or from an operating\r
661 system specific randomness source if available.\r
662\r
663 If a is not None or an int or long, hash(a) is used instead.\r
664\r
665 If a is an int or long, a is used directly. Distinct values between\r
666 0 and 27814431486575L inclusive are guaranteed to yield distinct\r
667 internal states (this guarantee is specific to the default\r
668 Wichmann-Hill generator).\r
669 """\r
670\r
671 if a is None:\r
672 try:\r
673 a = long(_hexlify(_urandom(16)), 16)\r
674 except NotImplementedError:\r
675 import time\r
676 a = long(time.time() * 256) # use fractional seconds\r
677\r
678 if not isinstance(a, (int, long)):\r
679 a = hash(a)\r
680\r
681 a, x = divmod(a, 30268)\r
682 a, y = divmod(a, 30306)\r
683 a, z = divmod(a, 30322)\r
684 self._seed = int(x)+1, int(y)+1, int(z)+1\r
685\r
686 self.gauss_next = None\r
687\r
688 def random(self):\r
689 """Get the next random number in the range [0.0, 1.0)."""\r
690\r
691 # Wichman-Hill random number generator.\r
692 #\r
693 # Wichmann, B. A. & Hill, I. D. (1982)\r
694 # Algorithm AS 183:\r
695 # An efficient and portable pseudo-random number generator\r
696 # Applied Statistics 31 (1982) 188-190\r
697 #\r
698 # see also:\r
699 # Correction to Algorithm AS 183\r
700 # Applied Statistics 33 (1984) 123\r
701 #\r
702 # McLeod, A. I. (1985)\r
703 # A remark on Algorithm AS 183\r
704 # Applied Statistics 34 (1985),198-200\r
705\r
706 # This part is thread-unsafe:\r
707 # BEGIN CRITICAL SECTION\r
708 x, y, z = self._seed\r
709 x = (171 * x) % 30269\r
710 y = (172 * y) % 30307\r
711 z = (170 * z) % 30323\r
712 self._seed = x, y, z\r
713 # END CRITICAL SECTION\r
714\r
715 # Note: on a platform using IEEE-754 double arithmetic, this can\r
716 # never return 0.0 (asserted by Tim; proof too long for a comment).\r
717 return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0\r
718\r
719 def getstate(self):\r
720 """Return internal state; can be passed to setstate() later."""\r
721 return self.VERSION, self._seed, self.gauss_next\r
722\r
723 def setstate(self, state):\r
724 """Restore internal state from object returned by getstate()."""\r
725 version = state[0]\r
726 if version == 1:\r
727 version, self._seed, self.gauss_next = state\r
728 else:\r
729 raise ValueError("state with version %s passed to "\r
730 "Random.setstate() of version %s" %\r
731 (version, self.VERSION))\r
732\r
733 def jumpahead(self, n):\r
734 """Act as if n calls to random() were made, but quickly.\r
735\r
736 n is an int, greater than or equal to 0.\r
737\r
738 Example use: If you have 2 threads and know that each will\r
739 consume no more than a million random numbers, create two Random\r
740 objects r1 and r2, then do\r
741 r2.setstate(r1.getstate())\r
742 r2.jumpahead(1000000)\r
743 Then r1 and r2 will use guaranteed-disjoint segments of the full\r
744 period.\r
745 """\r
746\r
747 if not n >= 0:\r
748 raise ValueError("n must be >= 0")\r
749 x, y, z = self._seed\r
750 x = int(x * pow(171, n, 30269)) % 30269\r
751 y = int(y * pow(172, n, 30307)) % 30307\r
752 z = int(z * pow(170, n, 30323)) % 30323\r
753 self._seed = x, y, z\r
754\r
755 def __whseed(self, x=0, y=0, z=0):\r
756 """Set the Wichmann-Hill seed from (x, y, z).\r
757\r
758 These must be integers in the range [0, 256).\r
759 """\r
760\r
761 if not type(x) == type(y) == type(z) == int:\r
762 raise TypeError('seeds must be integers')\r
763 if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256):\r
764 raise ValueError('seeds must be in range(0, 256)')\r
765 if 0 == x == y == z:\r
766 # Initialize from current time\r
767 import time\r
768 t = long(time.time() * 256)\r
769 t = int((t&0xffffff) ^ (t>>24))\r
770 t, x = divmod(t, 256)\r
771 t, y = divmod(t, 256)\r
772 t, z = divmod(t, 256)\r
773 # Zero is a poor seed, so substitute 1\r
774 self._seed = (x or 1, y or 1, z or 1)\r
775\r
776 self.gauss_next = None\r
777\r
778 def whseed(self, a=None):\r
779 """Seed from hashable object's hash code.\r
780\r
781 None or no argument seeds from current time. It is not guaranteed\r
782 that objects with distinct hash codes lead to distinct internal\r
783 states.\r
784\r
785 This is obsolete, provided for compatibility with the seed routine\r
786 used prior to Python 2.1. Use the .seed() method instead.\r
787 """\r
788\r
789 if a is None:\r
790 self.__whseed()\r
791 return\r
792 a = hash(a)\r
793 a, x = divmod(a, 256)\r
794 a, y = divmod(a, 256)\r
795 a, z = divmod(a, 256)\r
796 x = (x + a) % 256 or 1\r
797 y = (y + a) % 256 or 1\r
798 z = (z + a) % 256 or 1\r
799 self.__whseed(x, y, z)\r
800\r
801## --------------- Operating System Random Source ------------------\r
802\r
803class SystemRandom(Random):\r
804 """Alternate random number generator using sources provided\r
805 by the operating system (such as /dev/urandom on Unix or\r
806 CryptGenRandom on Windows).\r
807\r
808 Not available on all systems (see os.urandom() for details).\r
809 """\r
810\r
811 def random(self):\r
812 """Get the next random number in the range [0.0, 1.0)."""\r
813 return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF\r
814\r
815 def getrandbits(self, k):\r
816 """getrandbits(k) -> x. Generates a long int with k random bits."""\r
817 if k <= 0:\r
818 raise ValueError('number of bits must be greater than zero')\r
819 if k != int(k):\r
820 raise TypeError('number of bits should be an integer')\r
821 bytes = (k + 7) // 8 # bits / 8 and rounded up\r
822 x = long(_hexlify(_urandom(bytes)), 16)\r
823 return x >> (bytes * 8 - k) # trim excess bits\r
824\r
825 def _stub(self, *args, **kwds):\r
826 "Stub method. Not used for a system random number generator."\r
827 return None\r
828 seed = jumpahead = _stub\r
829\r
830 def _notimplemented(self, *args, **kwds):\r
831 "Method should not be called for a system random number generator."\r
832 raise NotImplementedError('System entropy source does not have state.')\r
833 getstate = setstate = _notimplemented\r
834\r
835## -------------------- test program --------------------\r
836\r
837def _test_generator(n, func, args):\r
838 import time\r
839 print n, 'times', func.__name__\r
840 total = 0.0\r
841 sqsum = 0.0\r
842 smallest = 1e10\r
843 largest = -1e10\r
844 t0 = time.time()\r
845 for i in range(n):\r
846 x = func(*args)\r
847 total += x\r
848 sqsum = sqsum + x*x\r
849 smallest = min(x, smallest)\r
850 largest = max(x, largest)\r
851 t1 = time.time()\r
852 print round(t1-t0, 3), 'sec,',\r
853 avg = total/n\r
854 stddev = _sqrt(sqsum/n - avg*avg)\r
855 print 'avg %g, stddev %g, min %g, max %g' % \\r
856 (avg, stddev, smallest, largest)\r
857\r
858\r
859def _test(N=2000):\r
860 _test_generator(N, random, ())\r
861 _test_generator(N, normalvariate, (0.0, 1.0))\r
862 _test_generator(N, lognormvariate, (0.0, 1.0))\r
863 _test_generator(N, vonmisesvariate, (0.0, 1.0))\r
864 _test_generator(N, gammavariate, (0.01, 1.0))\r
865 _test_generator(N, gammavariate, (0.1, 1.0))\r
866 _test_generator(N, gammavariate, (0.1, 2.0))\r
867 _test_generator(N, gammavariate, (0.5, 1.0))\r
868 _test_generator(N, gammavariate, (0.9, 1.0))\r
869 _test_generator(N, gammavariate, (1.0, 1.0))\r
870 _test_generator(N, gammavariate, (2.0, 1.0))\r
871 _test_generator(N, gammavariate, (20.0, 1.0))\r
872 _test_generator(N, gammavariate, (200.0, 1.0))\r
873 _test_generator(N, gauss, (0.0, 1.0))\r
874 _test_generator(N, betavariate, (3.0, 3.0))\r
875 _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0))\r
876\r
877# Create one instance, seeded from current time, and export its methods\r
878# as module-level functions. The functions share state across all uses\r
879#(both in the user's code and in the Python libraries), but that's fine\r
880# for most programs and is easier for the casual user than making them\r
881# instantiate their own Random() instance.\r
882\r
883_inst = Random()\r
884seed = _inst.seed\r
885random = _inst.random\r
886uniform = _inst.uniform\r
887triangular = _inst.triangular\r
888randint = _inst.randint\r
889choice = _inst.choice\r
890randrange = _inst.randrange\r
891sample = _inst.sample\r
892shuffle = _inst.shuffle\r
893normalvariate = _inst.normalvariate\r
894lognormvariate = _inst.lognormvariate\r
895expovariate = _inst.expovariate\r
896vonmisesvariate = _inst.vonmisesvariate\r
897gammavariate = _inst.gammavariate\r
898gauss = _inst.gauss\r
899betavariate = _inst.betavariate\r
900paretovariate = _inst.paretovariate\r
901weibullvariate = _inst.weibullvariate\r
902getstate = _inst.getstate\r
903setstate = _inst.setstate\r
904jumpahead = _inst.jumpahead\r
905getrandbits = _inst.getrandbits\r
906\r
907if __name__ == '__main__':\r
908 _test()\r