random.py 30 KB

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