random.py 32 KB

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