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