blob: a22449cfe69eb1af8e1fc5bb93da010ade8ab222 [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
10 generate random permutation
11
Guido van Rossume7b146f2000-02-04 15:28:42 +000012 distributions on the real line:
13 ------------------------------
Tim Petersd7b5e882001-01-25 03:36:26 +000014 uniform
Guido van Rossume7b146f2000-02-04 15:28:42 +000015 normal (Gaussian)
16 lognormal
17 negative exponential
18 gamma
19 beta
Guido van Rossumff03b1a1994-03-09 12:55:02 +000020
Guido van Rossume7b146f2000-02-04 15:28:42 +000021 distributions on the circle (angles 0 to 2pi)
22 ---------------------------------------------
23 circular uniform
24 von Mises
25
26Translated from anonymously contributed C/C++ source.
27
28Multi-threading note: the random number generator used here is not
29thread-safe; it is possible that two calls return the same random
Tim Peterscd804102001-01-25 20:25:57 +000030value. But you can instantiate a different instance of Random() in
31each thread to get generators that don't share state, then use
32.setstate() and .jumpahead() to move the generators to disjoint
33segments of the full period.
Guido van Rossume7b146f2000-02-04 15:28:42 +000034"""
Tim Petersd7b5e882001-01-25 03:36:26 +000035# XXX The docstring sucks.
Guido van Rossumd03e1191998-05-29 17:51:31 +000036
Tim Petersd7b5e882001-01-25 03:36:26 +000037from math import log as _log, exp as _exp, pi as _pi, e as _e
38from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
Guido van Rossumff03b1a1994-03-09 12:55:02 +000039
Tim Petersd7b5e882001-01-25 03:36:26 +000040def _verify(name, expected):
Tim Peters0c9886d2001-01-15 01:18:21 +000041 computed = eval(name)
42 if abs(computed - expected) > 1e-7:
Tim Petersd7b5e882001-01-25 03:36:26 +000043 raise ValueError(
44 "computed value for %s deviates too much "
45 "(computed %g, expected %g)" % (name, computed, expected))
46
47NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
48_verify('NV_MAGICCONST', 1.71552776992141)
49
50TWOPI = 2.0*_pi
51_verify('TWOPI', 6.28318530718)
52
53LOG4 = _log(4.0)
54_verify('LOG4', 1.38629436111989)
55
56SG_MAGICCONST = 1.0 + _log(4.5)
57_verify('SG_MAGICCONST', 2.50407739677627)
58
59del _verify
60
61# Translated by Guido van Rossum from C source provided by
62# Adrian Baddeley.
63
64class Random:
65
66 VERSION = 1 # used by getstate/setstate
67
68 def __init__(self, x=None):
69 """Initialize an instance.
70
71 Optional argument x controls seeding, as for Random.seed().
72 """
73
74 self.seed(x)
75 self.gauss_next = None
76
Tim Peterscd804102001-01-25 20:25:57 +000077## -------------------- core generator -------------------
78
Tim Petersd7b5e882001-01-25 03:36:26 +000079 # Specific to Wichmann-Hill generator. Subclasses wishing to use a
Tim Petersd52269b2001-01-25 06:23:18 +000080 # different core generator should override the seed(), random(),
Tim Peterscd804102001-01-25 20:25:57 +000081 # getstate(), setstate() and jumpahead() methods.
Tim Petersd7b5e882001-01-25 03:36:26 +000082
83 def __whseed(self, x=0, y=0, z=0):
84 """Set the Wichmann-Hill seed from (x, y, z).
85
86 These must be integers in the range [0, 256).
87 """
88
89 if not type(x) == type(y) == type(z) == type(0):
90 raise TypeError('seeds must be integers')
91 if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256):
92 raise ValueError('seeds must be in range(0, 256)')
93 if 0 == x == y == z:
94 # Initialize from current time
95 import time
96 t = long(time.time()) * 256
97 t = int((t&0xffffff) ^ (t>>24))
98 t, x = divmod(t, 256)
99 t, y = divmod(t, 256)
100 t, z = divmod(t, 256)
101 # Zero is a poor seed, so substitute 1
102 self._seed = (x or 1, y or 1, z or 1)
103
Tim Petersd7b5e882001-01-25 03:36:26 +0000104 def random(self):
105 """Get the next random number in the range [0.0, 1.0)."""
106
107 # Wichman-Hill random number generator.
108 #
109 # Wichmann, B. A. & Hill, I. D. (1982)
110 # Algorithm AS 183:
111 # An efficient and portable pseudo-random number generator
112 # Applied Statistics 31 (1982) 188-190
113 #
114 # see also:
115 # Correction to Algorithm AS 183
116 # Applied Statistics 33 (1984) 123
117 #
118 # McLeod, A. I. (1985)
119 # A remark on Algorithm AS 183
120 # Applied Statistics 34 (1985),198-200
121
122 # This part is thread-unsafe:
123 # BEGIN CRITICAL SECTION
124 x, y, z = self._seed
125 x = (171 * x) % 30269
126 y = (172 * y) % 30307
127 z = (170 * z) % 30323
128 self._seed = x, y, z
129 # END CRITICAL SECTION
130
131 # Note: on a platform using IEEE-754 double arithmetic, this can
132 # never return 0.0 (asserted by Tim; proof too long for a comment).
133 return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
134
Tim Peterscd804102001-01-25 20:25:57 +0000135 def seed(self, a=None):
136 """Seed from hashable object's hash code.
137
138 None or no argument seeds from current time. It is not guaranteed
139 that objects with distinct hash codes lead to distinct internal
140 states.
141 """
142
143 if a is None:
144 self.__whseed()
145 return
146 a = hash(a)
147 a, x = divmod(a, 256)
148 a, y = divmod(a, 256)
149 a, z = divmod(a, 256)
150 x = (x + a) % 256 or 1
151 y = (y + a) % 256 or 1
152 z = (z + a) % 256 or 1
153 self.__whseed(x, y, z)
154
155 def getstate(self):
156 """Return internal state; can be passed to setstate() later."""
157 return self.VERSION, self._seed, self.gauss_next
158
159 def setstate(self, state):
160 """Restore internal state from object returned by getstate()."""
161 version = state[0]
162 if version == 1:
163 version, self._seed, self.gauss_next = state
164 else:
165 raise ValueError("state with version %s passed to "
166 "Random.setstate() of version %s" %
167 (version, self.VERSION))
168
169 def jumpahead(self, n):
170 """Act as if n calls to random() were made, but quickly.
171
172 n is an int, greater than or equal to 0.
173
174 Example use: If you have 2 threads and know that each will
175 consume no more than a million random numbers, create two Random
176 objects r1 and r2, then do
177 r2.setstate(r1.getstate())
178 r2.jumpahead(1000000)
179 Then r1 and r2 will use guaranteed-disjoint segments of the full
180 period.
181 """
182
183 if not n >= 0:
184 raise ValueError("n must be >= 0")
185 x, y, z = self._seed
186 x = int(x * pow(171, n, 30269)) % 30269
187 y = int(y * pow(172, n, 30307)) % 30307
188 z = int(z * pow(170, n, 30323)) % 30323
189 self._seed = x, y, z
190
191## ---- Methods below this point do not need to be overridden when
192## ---- subclassing for the purpose of using a different core generator.
193
194## -------------------- pickle support -------------------
195
196 def __getstate__(self): # for pickle
197 return self.getstate()
198
199 def __setstate__(self, state): # for pickle
200 self.setstate(state)
201
202## -------------------- integer methods -------------------
203
Tim Petersd7b5e882001-01-25 03:36:26 +0000204 def randrange(self, start, stop=None, step=1, int=int, default=None):
205 """Choose a random item from range(start, stop[, step]).
206
207 This fixes the problem with randint() which includes the
208 endpoint; in Python this is usually not what you want.
209 Do not supply the 'int' and 'default' arguments.
210 """
211
212 # This code is a bit messy to make it fast for the
213 # common case while still doing adequate error checking
214 istart = int(start)
215 if istart != start:
216 raise ValueError, "non-integer arg 1 for randrange()"
217 if stop is default:
218 if istart > 0:
219 return int(self.random() * istart)
220 raise ValueError, "empty range for randrange()"
221 istop = int(stop)
222 if istop != stop:
223 raise ValueError, "non-integer stop for randrange()"
224 if step == 1:
225 if istart < istop:
226 return istart + int(self.random() *
227 (istop - istart))
228 raise ValueError, "empty range for randrange()"
229 istep = int(step)
230 if istep != step:
231 raise ValueError, "non-integer step for randrange()"
232 if istep > 0:
233 n = (istop - istart + istep - 1) / istep
234 elif istep < 0:
235 n = (istop - istart + istep + 1) / istep
236 else:
237 raise ValueError, "zero step for randrange()"
238
239 if n <= 0:
240 raise ValueError, "empty range for randrange()"
241 return istart + istep*int(self.random() * n)
242
243 def randint(self, a, b):
Tim Peterscd804102001-01-25 20:25:57 +0000244 """Return random integer in range [a, b], including both end points.
Tim Petersd7b5e882001-01-25 03:36:26 +0000245
Tim Peterscd804102001-01-25 20:25:57 +0000246 (Deprecated; use randrange(a, b+1).)
Tim Petersd7b5e882001-01-25 03:36:26 +0000247 """
248
249 return self.randrange(a, b+1)
250
Tim Peterscd804102001-01-25 20:25:57 +0000251## -------------------- sequence methods -------------------
252
Tim Petersd7b5e882001-01-25 03:36:26 +0000253 def choice(self, seq):
254 """Choose a random element from a non-empty sequence."""
255 return seq[int(self.random() * len(seq))]
256
257 def shuffle(self, x, random=None, int=int):
258 """x, random=random.random -> shuffle list x in place; return None.
259
260 Optional arg random is a 0-argument function returning a random
261 float in [0.0, 1.0); by default, the standard random.random.
262
263 Note that for even rather small len(x), the total number of
264 permutations of x is larger than the period of most random number
265 generators; this implies that "most" permutations of a long
266 sequence can never be generated.
267 """
268
269 if random is None:
270 random = self.random
271 for i in xrange(len(x)-1, 0, -1):
Tim Peterscd804102001-01-25 20:25:57 +0000272 # pick an element in x[:i+1] with which to exchange x[i]
Tim Petersd7b5e882001-01-25 03:36:26 +0000273 j = int(random() * (i+1))
274 x[i], x[j] = x[j], x[i]
275
Tim Peterscd804102001-01-25 20:25:57 +0000276## -------------------- real-valued distributions -------------------
277
278## -------------------- uniform distribution -------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000279
280 def uniform(self, a, b):
281 """Get a random number in the range [a, b)."""
282 return a + (b-a) * self.random()
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000283
Tim Peterscd804102001-01-25 20:25:57 +0000284## -------------------- normal distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000285
Tim Petersd7b5e882001-01-25 03:36:26 +0000286 def normalvariate(self, mu, sigma):
287 # mu = mean, sigma = standard deviation
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000288
Tim Petersd7b5e882001-01-25 03:36:26 +0000289 # Uses Kinderman and Monahan method. Reference: Kinderman,
290 # A.J. and Monahan, J.F., "Computer generation of random
291 # variables using the ratio of uniform deviates", ACM Trans
292 # Math Software, 3, (1977), pp257-260.
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000293
Tim Petersd7b5e882001-01-25 03:36:26 +0000294 random = self.random
Tim Peters0c9886d2001-01-15 01:18:21 +0000295 while 1:
296 u1 = random()
297 u2 = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000298 z = NV_MAGICCONST*(u1-0.5)/u2
299 zz = z*z/4.0
300 if zz <= -_log(u2):
301 break
302 return mu + z*sigma
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000303
Tim Peterscd804102001-01-25 20:25:57 +0000304## -------------------- lognormal distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000305
306 def lognormvariate(self, mu, sigma):
307 return _exp(self.normalvariate(mu, sigma))
308
Tim Peterscd804102001-01-25 20:25:57 +0000309## -------------------- circular uniform --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000310
311 def cunifvariate(self, mean, arc):
312 # mean: mean angle (in radians between 0 and pi)
313 # arc: range of distribution (in radians between 0 and pi)
314
315 return (mean + arc * (self.random() - 0.5)) % _pi
316
Tim Peterscd804102001-01-25 20:25:57 +0000317## -------------------- exponential distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000318
319 def expovariate(self, lambd):
320 # lambd: rate lambd = 1/mean
321 # ('lambda' is a Python reserved word)
322
323 random = self.random
Tim Peters0c9886d2001-01-15 01:18:21 +0000324 u = random()
325 while u <= 1e-7:
326 u = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000327 return -_log(u)/lambd
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000328
Tim Peterscd804102001-01-25 20:25:57 +0000329## -------------------- von Mises distribution --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000330
Tim Petersd7b5e882001-01-25 03:36:26 +0000331 def vonmisesvariate(self, mu, kappa):
332 # mu: mean angle (in radians between 0 and 2*pi)
333 # kappa: concentration parameter kappa (>= 0)
334 # if kappa = 0 generate uniform random angle
335
336 # Based upon an algorithm published in: Fisher, N.I.,
337 # "Statistical Analysis of Circular Data", Cambridge
338 # University Press, 1993.
339
340 # Thanks to Magnus Kessler for a correction to the
341 # implementation of step 4.
342
343 random = self.random
344 if kappa <= 1e-6:
345 return TWOPI * random()
346
347 a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)
348 b = (a - _sqrt(2.0 * a))/(2.0 * kappa)
349 r = (1.0 + b * b)/(2.0 * b)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000350
Tim Peters0c9886d2001-01-15 01:18:21 +0000351 while 1:
Tim Peters0c9886d2001-01-15 01:18:21 +0000352 u1 = random()
Tim Petersd7b5e882001-01-25 03:36:26 +0000353
354 z = _cos(_pi * u1)
355 f = (1.0 + r * z)/(r + z)
356 c = kappa * (r - f)
357
358 u2 = random()
359
360 if not (u2 >= c * (2.0 - c) and u2 > c * _exp(1.0 - c)):
Tim Peters0c9886d2001-01-15 01:18:21 +0000361 break
Tim Petersd7b5e882001-01-25 03:36:26 +0000362
363 u3 = random()
364 if u3 > 0.5:
365 theta = (mu % TWOPI) + _acos(f)
366 else:
367 theta = (mu % TWOPI) - _acos(f)
368
369 return theta
370
Tim Peterscd804102001-01-25 20:25:57 +0000371## -------------------- gamma distribution --------------------
Tim Petersd7b5e882001-01-25 03:36:26 +0000372
373 def gammavariate(self, alpha, beta):
374 # beta times standard gamma
375 ainv = _sqrt(2.0 * alpha - 1.0)
376 return beta * self.stdgamma(alpha, ainv, alpha - LOG4, alpha + ainv)
377
378 def stdgamma(self, alpha, ainv, bbb, ccc):
379 # ainv = sqrt(2 * alpha - 1)
380 # bbb = alpha - log(4)
381 # ccc = alpha + ainv
382
383 random = self.random
384 if alpha <= 0.0:
385 raise ValueError, 'stdgamma: alpha must be > 0.0'
386
387 if alpha > 1.0:
388
389 # Uses R.C.H. Cheng, "The generation of Gamma
390 # variables with non-integral shape parameters",
391 # Applied Statistics, (1977), 26, No. 1, p71-74
392
393 while 1:
394 u1 = random()
395 u2 = random()
396 v = _log(u1/(1.0-u1))/ainv
397 x = alpha*_exp(v)
398 z = u1*u1*u2
399 r = bbb+ccc*v-x
400 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
401 return x
402
403 elif alpha == 1.0:
404 # expovariate(1)
405 u = random()
406 while u <= 1e-7:
407 u = random()
408 return -_log(u)
409
410 else: # alpha is between 0 and 1 (exclusive)
411
412 # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
413
414 while 1:
415 u = random()
416 b = (_e + alpha)/_e
417 p = b*u
418 if p <= 1.0:
419 x = pow(p, 1.0/alpha)
420 else:
421 # p > 1
422 x = -_log((b-p)/alpha)
423 u1 = random()
424 if not (((p <= 1.0) and (u1 > _exp(-x))) or
425 ((p > 1) and (u1 > pow(x, alpha - 1.0)))):
426 break
427 return x
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000428
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000429
Tim Peterscd804102001-01-25 20:25:57 +0000430## -------------------- Gauss (faster alternative) --------------------
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000431
Tim Petersd7b5e882001-01-25 03:36:26 +0000432 def gauss(self, mu, sigma):
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000433
Tim Petersd7b5e882001-01-25 03:36:26 +0000434 # When x and y are two variables from [0, 1), uniformly
435 # distributed, then
436 #
437 # cos(2*pi*x)*sqrt(-2*log(1-y))
438 # sin(2*pi*x)*sqrt(-2*log(1-y))
439 #
440 # are two *independent* variables with normal distribution
441 # (mu = 0, sigma = 1).
442 # (Lambert Meertens)
443 # (corrected version; bug discovered by Mike Miller, fixed by LM)
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000444
Tim Petersd7b5e882001-01-25 03:36:26 +0000445 # Multithreading note: When two threads call this function
446 # simultaneously, it is possible that they will receive the
447 # same return value. The window is very small though. To
448 # avoid this, you have to use a lock around all calls. (I
449 # didn't want to slow this down in the serial case by using a
450 # lock here.)
Guido van Rossumd03e1191998-05-29 17:51:31 +0000451
Tim Petersd7b5e882001-01-25 03:36:26 +0000452 random = self.random
453 z = self.gauss_next
454 self.gauss_next = None
455 if z is None:
456 x2pi = random() * TWOPI
457 g2rad = _sqrt(-2.0 * _log(1.0 - random()))
458 z = _cos(x2pi) * g2rad
459 self.gauss_next = _sin(x2pi) * g2rad
Guido van Rossumcc32ac91994-03-15 16:10:24 +0000460
Tim Petersd7b5e882001-01-25 03:36:26 +0000461 return mu + z*sigma
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000462
Tim Peterscd804102001-01-25 20:25:57 +0000463## -------------------- beta --------------------
Tim Peters85e2e472001-01-26 06:49:56 +0000464## See
465## http://sourceforge.net/bugs/?func=detailbug&bug_id=130030&group_id=5470
466## for Ivan Frohne's insightful analysis of why the original implementation:
467##
468## def betavariate(self, alpha, beta):
469## # Discrete Event Simulation in C, pp 87-88.
470##
471## y = self.expovariate(alpha)
472## z = self.expovariate(1.0/beta)
473## return z/(y+z)
474##
475## was dead wrong, and how it probably got that way.
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000476
Tim Petersd7b5e882001-01-25 03:36:26 +0000477 def betavariate(self, alpha, beta):
Tim Peters85e2e472001-01-26 06:49:56 +0000478 # This version due to Janne Sinkkonen, and matches all the std
479 # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
480 y = self.gammavariate(alpha, 1.)
481 if y == 0:
482 return 0.0
483 else:
484 return y / (y + self.gammavariate(beta, 1.))
Guido van Rossum95bfcda1994-03-09 14:21:05 +0000485
Tim Peterscd804102001-01-25 20:25:57 +0000486## -------------------- Pareto --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000487
Tim Petersd7b5e882001-01-25 03:36:26 +0000488 def paretovariate(self, alpha):
489 # Jain, pg. 495
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000490
Tim Petersd7b5e882001-01-25 03:36:26 +0000491 u = self.random()
492 return 1.0 / pow(u, 1.0/alpha)
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000493
Tim Peterscd804102001-01-25 20:25:57 +0000494## -------------------- Weibull --------------------
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000495
Tim Petersd7b5e882001-01-25 03:36:26 +0000496 def weibullvariate(self, alpha, beta):
497 # Jain, pg. 499; bug fix courtesy Bill Arms
Guido van Rossumcf4559a1997-12-02 02:47:39 +0000498
Tim Petersd7b5e882001-01-25 03:36:26 +0000499 u = self.random()
500 return alpha * pow(-_log(u), 1.0/beta)
Guido van Rossum6c395ba1999-08-18 13:53:28 +0000501
Tim Peterscd804102001-01-25 20:25:57 +0000502## -------------------- test program --------------------
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000503
Tim Petersd7b5e882001-01-25 03:36:26 +0000504def _test_generator(n, funccall):
Tim Peters0c9886d2001-01-15 01:18:21 +0000505 import time
506 print n, 'times', funccall
507 code = compile(funccall, funccall, 'eval')
508 sum = 0.0
509 sqsum = 0.0
510 smallest = 1e10
511 largest = -1e10
512 t0 = time.time()
513 for i in range(n):
514 x = eval(code)
515 sum = sum + x
516 sqsum = sqsum + x*x
517 smallest = min(x, smallest)
518 largest = max(x, largest)
519 t1 = time.time()
520 print round(t1-t0, 3), 'sec,',
521 avg = sum/n
Tim Petersd7b5e882001-01-25 03:36:26 +0000522 stddev = _sqrt(sqsum/n - avg*avg)
Tim Peters0c9886d2001-01-15 01:18:21 +0000523 print 'avg %g, stddev %g, min %g, max %g' % \
524 (avg, stddev, smallest, largest)
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000525
Tim Petersd7b5e882001-01-25 03:36:26 +0000526def _test(N=200):
527 print 'TWOPI =', TWOPI
528 print 'LOG4 =', LOG4
529 print 'NV_MAGICCONST =', NV_MAGICCONST
530 print 'SG_MAGICCONST =', SG_MAGICCONST
531 _test_generator(N, 'random()')
532 _test_generator(N, 'normalvariate(0.0, 1.0)')
533 _test_generator(N, 'lognormvariate(0.0, 1.0)')
534 _test_generator(N, 'cunifvariate(0.0, 1.0)')
535 _test_generator(N, 'expovariate(1.0)')
536 _test_generator(N, 'vonmisesvariate(0.0, 1.0)')
537 _test_generator(N, 'gammavariate(0.5, 1.0)')
538 _test_generator(N, 'gammavariate(0.9, 1.0)')
539 _test_generator(N, 'gammavariate(1.0, 1.0)')
540 _test_generator(N, 'gammavariate(2.0, 1.0)')
541 _test_generator(N, 'gammavariate(20.0, 1.0)')
542 _test_generator(N, 'gammavariate(200.0, 1.0)')
543 _test_generator(N, 'gauss(0.0, 1.0)')
544 _test_generator(N, 'betavariate(3.0, 3.0)')
545 _test_generator(N, 'paretovariate(1.0)')
546 _test_generator(N, 'weibullvariate(1.0, 1.0)')
547
Tim Peterscd804102001-01-25 20:25:57 +0000548 # Test jumpahead.
549 s = getstate()
550 jumpahead(N)
551 r1 = random()
552 # now do it the slow way
553 setstate(s)
554 for i in range(N):
555 random()
556 r2 = random()
557 if r1 != r2:
558 raise ValueError("jumpahead test failed " + `(N, r1, r2)`)
559
Tim Petersd7b5e882001-01-25 03:36:26 +0000560# Initialize from current time.
561_inst = Random()
562seed = _inst.seed
563random = _inst.random
564uniform = _inst.uniform
565randint = _inst.randint
566choice = _inst.choice
567randrange = _inst.randrange
568shuffle = _inst.shuffle
569normalvariate = _inst.normalvariate
570lognormvariate = _inst.lognormvariate
571cunifvariate = _inst.cunifvariate
572expovariate = _inst.expovariate
573vonmisesvariate = _inst.vonmisesvariate
574gammavariate = _inst.gammavariate
575stdgamma = _inst.stdgamma
576gauss = _inst.gauss
577betavariate = _inst.betavariate
578paretovariate = _inst.paretovariate
579weibullvariate = _inst.weibullvariate
580getstate = _inst.getstate
581setstate = _inst.setstate
Tim Petersd52269b2001-01-25 06:23:18 +0000582jumpahead = _inst.jumpahead
Tim Petersd7b5e882001-01-25 03:36:26 +0000583
Guido van Rossumff03b1a1994-03-09 12:55:02 +0000584if __name__ == '__main__':
Tim Petersd7b5e882001-01-25 03:36:26 +0000585 _test()