random.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. """Random variable generators.
  2. integers
  3. --------
  4. uniform within range
  5. sequences
  6. ---------
  7. pick random element
  8. pick random sample
  9. pick weighted random sample
  10. generate random permutation
  11. distributions on the real line:
  12. ------------------------------
  13. uniform
  14. triangular
  15. normal (Gaussian)
  16. lognormal
  17. negative exponential
  18. gamma
  19. beta
  20. pareto
  21. Weibull
  22. distributions on the circle (angles 0 to 2pi)
  23. ---------------------------------------------
  24. circular uniform
  25. von Mises
  26. General notes on the underlying Mersenne Twister core generator:
  27. * The period is 2**19937-1.
  28. * It is one of the most extensively tested generators in existence.
  29. * The random() method is implemented in C, executes in a single Python step,
  30. and is, therefore, threadsafe.
  31. """
  32. from warnings import warn as _warn
  33. from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
  34. from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
  35. from os import urandom as _urandom
  36. from _collections_abc import Set as _Set, Sequence as _Sequence
  37. from itertools import accumulate as _accumulate, repeat as _repeat
  38. from bisect import bisect as _bisect
  39. import os as _os
  40. try:
  41. # hashlib is pretty heavy to load, try lean internal module first
  42. from _sha512 import sha512 as _sha512
  43. except ImportError:
  44. # fallback to official implementation
  45. from hashlib import sha512 as _sha512
  46. __all__ = ["Random","seed","random","uniform","randint","choice","sample",
  47. "randrange","shuffle","normalvariate","lognormvariate",
  48. "expovariate","vonmisesvariate","gammavariate","triangular",
  49. "gauss","betavariate","paretovariate","weibullvariate",
  50. "getstate","setstate", "getrandbits", "choices",
  51. "SystemRandom"]
  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. RECIP_BPF = 2**-BPF
  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 and os.urandom() core generators.
  61. import _random
  62. class Random(_random.Random):
  63. """Random number generator base class used by bound module functions.
  64. Used to instantiate instances of Random to get generators that don't
  65. share state.
  66. Class Random can also be subclassed if you want to use a different basic
  67. generator of your own devising: in that case, override the following
  68. methods: random(), seed(), getstate(), and setstate().
  69. Optionally, implement a getrandbits() method so that randrange()
  70. can cover arbitrarily large ranges.
  71. """
  72. VERSION = 3 # used by getstate/setstate
  73. def __init__(self, x=None):
  74. """Initialize an instance.
  75. Optional argument x controls seeding, as for Random.seed().
  76. """
  77. self.seed(x)
  78. self.gauss_next = None
  79. def __init_subclass__(cls, /, **kwargs):
  80. """Control how subclasses generate random integers.
  81. The algorithm a subclass can use depends on the random() and/or
  82. getrandbits() implementation available to it and determines
  83. whether it can generate random integers from arbitrarily large
  84. ranges.
  85. """
  86. for c in cls.__mro__:
  87. if '_randbelow' in c.__dict__:
  88. # just inherit it
  89. break
  90. if 'getrandbits' in c.__dict__:
  91. cls._randbelow = cls._randbelow_with_getrandbits
  92. break
  93. if 'random' in c.__dict__:
  94. cls._randbelow = cls._randbelow_without_getrandbits
  95. break
  96. def seed(self, a=None, version=2):
  97. """Initialize internal state from hashable object.
  98. None or no argument seeds from current time or from an operating
  99. system specific randomness source if available.
  100. If *a* is an int, all bits are used.
  101. For version 2 (the default), all of the bits are used if *a* is a str,
  102. bytes, or bytearray. For version 1 (provided for reproducing random
  103. sequences from older versions of Python), the algorithm for str and
  104. bytes generates a narrower range of seeds.
  105. """
  106. if version == 1 and isinstance(a, (str, bytes)):
  107. a = a.decode('latin-1') if isinstance(a, bytes) else a
  108. x = ord(a[0]) << 7 if a else 0
  109. for c in map(ord, a):
  110. x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF
  111. x ^= len(a)
  112. a = -2 if x == -1 else x
  113. if version == 2 and isinstance(a, (str, bytes, bytearray)):
  114. if isinstance(a, str):
  115. a = a.encode()
  116. a += _sha512(a).digest()
  117. a = int.from_bytes(a, 'big')
  118. super().seed(a)
  119. self.gauss_next = None
  120. def getstate(self):
  121. """Return internal state; can be passed to setstate() later."""
  122. return self.VERSION, super().getstate(), self.gauss_next
  123. def setstate(self, state):
  124. """Restore internal state from object returned by getstate()."""
  125. version = state[0]
  126. if version == 3:
  127. version, internalstate, self.gauss_next = state
  128. super().setstate(internalstate)
  129. elif version == 2:
  130. version, internalstate, self.gauss_next = state
  131. # In version 2, the state was saved as signed ints, which causes
  132. # inconsistencies between 32/64-bit systems. The state is
  133. # really unsigned 32-bit ints, so we convert negative ints from
  134. # version 2 to positive longs for version 3.
  135. try:
  136. internalstate = tuple(x % (2**32) for x in internalstate)
  137. except ValueError as e:
  138. raise TypeError from e
  139. super().setstate(internalstate)
  140. else:
  141. raise ValueError("state with version %s passed to "
  142. "Random.setstate() of version %s" %
  143. (version, self.VERSION))
  144. ## ---- Methods below this point do not need to be overridden when
  145. ## ---- subclassing for the purpose of using a different core generator.
  146. ## -------------------- pickle support -------------------
  147. # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
  148. # longer called; we leave it here because it has been here since random was
  149. # rewritten back in 2001 and why risk breaking something.
  150. def __getstate__(self): # for pickle
  151. return self.getstate()
  152. def __setstate__(self, state): # for pickle
  153. self.setstate(state)
  154. def __reduce__(self):
  155. return self.__class__, (), self.getstate()
  156. ## -------------------- integer methods -------------------
  157. def randrange(self, start, stop=None, step=1, _int=int):
  158. """Choose a random item from range(start, stop[, step]).
  159. This fixes the problem with randint() which includes the
  160. endpoint; in Python this is usually not what you want.
  161. """
  162. # This code is a bit messy to make it fast for the
  163. # common case while still doing adequate error checking.
  164. istart = _int(start)
  165. if istart != start:
  166. raise ValueError("non-integer arg 1 for randrange()")
  167. if stop is None:
  168. if istart > 0:
  169. return self._randbelow(istart)
  170. raise ValueError("empty range for randrange()")
  171. # stop argument supplied.
  172. istop = _int(stop)
  173. if istop != stop:
  174. raise ValueError("non-integer stop for randrange()")
  175. width = istop - istart
  176. if step == 1 and width > 0:
  177. return istart + self._randbelow(width)
  178. if step == 1:
  179. raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
  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. if n <= 0:
  191. raise ValueError("empty range for randrange()")
  192. return istart + istep*self._randbelow(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_with_getrandbits(self, n):
  198. "Return a random int in the range [0,n). Raises ValueError if n==0."
  199. getrandbits = self.getrandbits
  200. k = n.bit_length() # don't use (n-1) here because n can be 1
  201. r = getrandbits(k) # 0 <= r < 2**k
  202. while r >= n:
  203. r = getrandbits(k)
  204. return r
  205. def _randbelow_without_getrandbits(self, n, int=int, maxsize=1<<BPF):
  206. """Return a random int in the range [0,n). Raises ValueError if n==0.
  207. The implementation does not use getrandbits, but only random.
  208. """
  209. random = self.random
  210. if n >= maxsize:
  211. _warn("Underlying random() generator does not supply \n"
  212. "enough bits to choose from a population range this large.\n"
  213. "To remove the range limitation, add a getrandbits() method.")
  214. return int(random() * n)
  215. if n == 0:
  216. raise ValueError("Boundary cannot be zero")
  217. rem = maxsize % n
  218. limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
  219. r = random()
  220. while r >= limit:
  221. r = random()
  222. return int(r*maxsize) % n
  223. _randbelow = _randbelow_with_getrandbits
  224. ## -------------------- sequence methods -------------------
  225. def choice(self, seq):
  226. """Choose a random element from a non-empty sequence."""
  227. try:
  228. i = self._randbelow(len(seq))
  229. except ValueError:
  230. raise IndexError('Cannot choose from an empty sequence') from None
  231. return seq[i]
  232. def shuffle(self, x, random=None):
  233. """Shuffle list x in place, and return None.
  234. Optional argument random is a 0-argument function returning a
  235. random float in [0.0, 1.0); if it is the default None, the
  236. standard random.random will be used.
  237. """
  238. if random is None:
  239. randbelow = self._randbelow
  240. for i in reversed(range(1, len(x))):
  241. # pick an element in x[:i+1] with which to exchange x[i]
  242. j = randbelow(i+1)
  243. x[i], x[j] = x[j], x[i]
  244. else:
  245. _int = int
  246. for i in reversed(range(1, len(x))):
  247. # pick an element in x[:i+1] with which to exchange x[i]
  248. j = _int(random() * (i+1))
  249. x[i], x[j] = x[j], x[i]
  250. def sample(self, population, k):
  251. """Chooses k unique random elements from a population sequence or set.
  252. Returns a new list containing elements from the population while
  253. leaving the original population unchanged. The resulting list is
  254. in selection order so that all sub-slices will also be valid random
  255. samples. This allows raffle winners (the sample) to be partitioned
  256. into grand prize and second place winners (the subslices).
  257. Members of the population need not be hashable or unique. If the
  258. population contains repeats, then each occurrence is a possible
  259. selection in the sample.
  260. To choose a sample in a range of integers, use range as an argument.
  261. This is especially fast and space efficient for sampling from a
  262. large population: sample(range(10000000), 60)
  263. """
  264. # Sampling without replacement entails tracking either potential
  265. # selections (the pool) in a list or previous selections in a set.
  266. # When the number of selections is small compared to the
  267. # population, then tracking selections is efficient, requiring
  268. # only a small set and an occasional reselection. For
  269. # a larger number of selections, the pool tracking method is
  270. # preferred since the list takes less space than the
  271. # set and it doesn't suffer from frequent reselections.
  272. # The number of calls to _randbelow() is kept at or near k, the
  273. # theoretical minimum. This is important because running time
  274. # is dominated by _randbelow() and because it extracts the
  275. # least entropy from the underlying random number generators.
  276. # Memory requirements are kept to the smaller of a k-length
  277. # set or an n-length list.
  278. # There are other sampling algorithms that do not require
  279. # auxiliary memory, but they were rejected because they made
  280. # too many calls to _randbelow(), making them slower and
  281. # causing them to eat more entropy than necessary.
  282. if isinstance(population, _Set):
  283. population = tuple(population)
  284. if not isinstance(population, _Sequence):
  285. raise TypeError("Population must be a sequence or set. For dicts, use list(d).")
  286. randbelow = self._randbelow
  287. n = len(population)
  288. if not 0 <= k <= n:
  289. raise ValueError("Sample larger than population or is negative")
  290. result = [None] * k
  291. setsize = 21 # size of a small set minus size of an empty list
  292. if k > 5:
  293. setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
  294. if n <= setsize:
  295. # An n-length list is smaller than a k-length set
  296. pool = list(population)
  297. for i in range(k): # invariant: non-selected at [0,n-i)
  298. j = randbelow(n-i)
  299. result[i] = pool[j]
  300. pool[j] = pool[n-i-1] # move non-selected item into vacancy
  301. else:
  302. selected = set()
  303. selected_add = selected.add
  304. for i in range(k):
  305. j = randbelow(n)
  306. while j in selected:
  307. j = randbelow(n)
  308. selected_add(j)
  309. result[i] = population[j]
  310. return result
  311. def choices(self, population, weights=None, *, cum_weights=None, k=1):
  312. """Return a k sized list of population elements chosen with replacement.
  313. If the relative weights or cumulative weights are not specified,
  314. the selections are made with equal probability.
  315. """
  316. random = self.random
  317. n = len(population)
  318. if cum_weights is None:
  319. if weights is None:
  320. _int = int
  321. n += 0.0 # convert to float for a small speed improvement
  322. return [population[_int(random() * n)] for i in _repeat(None, k)]
  323. cum_weights = list(_accumulate(weights))
  324. elif weights is not None:
  325. raise TypeError('Cannot specify both weights and cumulative weights')
  326. if len(cum_weights) != n:
  327. raise ValueError('The number of weights does not match the population')
  328. bisect = _bisect
  329. total = cum_weights[-1] + 0.0 # convert to float
  330. hi = n - 1
  331. return [population[bisect(cum_weights, random() * total, 0, hi)]
  332. for i in _repeat(None, k)]
  333. ## -------------------- real-valued distributions -------------------
  334. ## -------------------- uniform distribution -------------------
  335. def uniform(self, a, b):
  336. "Get a random number in the range [a, b) or [a, b] depending on rounding."
  337. return a + (b-a) * self.random()
  338. ## -------------------- triangular --------------------
  339. def triangular(self, low=0.0, high=1.0, mode=None):
  340. """Triangular distribution.
  341. Continuous distribution bounded by given lower and upper limits,
  342. and having a given mode value in-between.
  343. http://en.wikipedia.org/wiki/Triangular_distribution
  344. """
  345. u = self.random()
  346. try:
  347. c = 0.5 if mode is None else (mode - low) / (high - low)
  348. except ZeroDivisionError:
  349. return low
  350. if u > c:
  351. u = 1.0 - u
  352. c = 1.0 - c
  353. low, high = high, low
  354. return low + (high - low) * _sqrt(u * c)
  355. ## -------------------- normal distribution --------------------
  356. def normalvariate(self, mu, sigma):
  357. """Normal distribution.
  358. mu is the mean, and sigma is the standard deviation.
  359. """
  360. # mu = mean, sigma = standard deviation
  361. # Uses Kinderman and Monahan method. Reference: Kinderman,
  362. # A.J. and Monahan, J.F., "Computer generation of random
  363. # variables using the ratio of uniform deviates", ACM Trans
  364. # Math Software, 3, (1977), pp257-260.
  365. random = self.random
  366. while 1:
  367. u1 = random()
  368. u2 = 1.0 - random()
  369. z = NV_MAGICCONST*(u1-0.5)/u2
  370. zz = z*z/4.0
  371. if zz <= -_log(u2):
  372. break
  373. return mu + z*sigma
  374. ## -------------------- lognormal distribution --------------------
  375. def lognormvariate(self, mu, sigma):
  376. """Log normal distribution.
  377. If you take the natural logarithm of this distribution, you'll get a
  378. normal distribution with mean mu and standard deviation sigma.
  379. mu can have any value, and sigma must be greater than zero.
  380. """
  381. return _exp(self.normalvariate(mu, sigma))
  382. ## -------------------- exponential distribution --------------------
  383. def expovariate(self, lambd):
  384. """Exponential distribution.
  385. lambd is 1.0 divided by the desired mean. It should be
  386. nonzero. (The parameter would be called "lambda", but that is
  387. a reserved word in Python.) Returned values range from 0 to
  388. positive infinity if lambd is positive, and from negative
  389. infinity to 0 if lambd is negative.
  390. """
  391. # lambd: rate lambd = 1/mean
  392. # ('lambda' is a Python reserved word)
  393. # we use 1-random() instead of random() to preclude the
  394. # possibility of taking the log of zero.
  395. return -_log(1.0 - self.random())/lambd
  396. ## -------------------- von Mises distribution --------------------
  397. def vonmisesvariate(self, mu, kappa):
  398. """Circular data distribution.
  399. mu is the mean angle, expressed in radians between 0 and 2*pi, and
  400. kappa is the concentration parameter, which must be greater than or
  401. equal to zero. If kappa is equal to zero, this distribution reduces
  402. to a uniform random angle over the range 0 to 2*pi.
  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. # Based upon an algorithm published in: Fisher, N.I.,
  408. # "Statistical Analysis of Circular Data", Cambridge
  409. # University Press, 1993.
  410. # Thanks to Magnus Kessler for a correction to the
  411. # implementation of step 4.
  412. random = self.random
  413. if kappa <= 1e-6:
  414. return TWOPI * random()
  415. s = 0.5 / kappa
  416. r = s + _sqrt(1.0 + s * s)
  417. while 1:
  418. u1 = random()
  419. z = _cos(_pi * u1)
  420. d = z / (r + z)
  421. u2 = random()
  422. if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d):
  423. break
  424. q = 1.0 / r
  425. f = (q + z) / (1.0 + q * z)
  426. u3 = random()
  427. if u3 > 0.5:
  428. theta = (mu + _acos(f)) % TWOPI
  429. else:
  430. theta = (mu - _acos(f)) % TWOPI
  431. return theta
  432. ## -------------------- gamma distribution --------------------
  433. def gammavariate(self, alpha, beta):
  434. """Gamma distribution. Not the gamma function!
  435. Conditions on the parameters are alpha > 0 and beta > 0.
  436. The probability distribution function is:
  437. x ** (alpha - 1) * math.exp(-x / beta)
  438. pdf(x) = --------------------------------------
  439. math.gamma(alpha) * beta ** alpha
  440. """
  441. # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
  442. # Warning: a few older sources define the gamma distribution in terms
  443. # of alpha > -1.0
  444. if alpha <= 0.0 or beta <= 0.0:
  445. raise ValueError('gammavariate: alpha and beta must be > 0.0')
  446. random = self.random
  447. if alpha > 1.0:
  448. # Uses R.C.H. Cheng, "The generation of Gamma
  449. # variables with non-integral shape parameters",
  450. # Applied Statistics, (1977), 26, No. 1, p71-74
  451. ainv = _sqrt(2.0 * alpha - 1.0)
  452. bbb = alpha - LOG4
  453. ccc = alpha + ainv
  454. while 1:
  455. u1 = random()
  456. if not 1e-7 < u1 < .9999999:
  457. continue
  458. u2 = 1.0 - random()
  459. v = _log(u1/(1.0-u1))/ainv
  460. x = alpha*_exp(v)
  461. z = u1*u1*u2
  462. r = bbb+ccc*v-x
  463. if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
  464. return x * beta
  465. elif alpha == 1.0:
  466. # expovariate(1/beta)
  467. return -_log(1.0 - random()) * beta
  468. else: # alpha is between 0 and 1 (exclusive)
  469. # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
  470. while 1:
  471. u = random()
  472. b = (_e + alpha)/_e
  473. p = b*u
  474. if p <= 1.0:
  475. x = p ** (1.0/alpha)
  476. else:
  477. x = -_log((b-p)/alpha)
  478. u1 = random()
  479. if p > 1.0:
  480. if u1 <= x ** (alpha - 1.0):
  481. break
  482. elif u1 <= _exp(-x):
  483. break
  484. return x * beta
  485. ## -------------------- Gauss (faster alternative) --------------------
  486. def gauss(self, mu, sigma):
  487. """Gaussian distribution.
  488. mu is the mean, and sigma is the standard deviation. This is
  489. slightly faster than the normalvariate() function.
  490. Not thread-safe without a lock around calls.
  491. """
  492. # When x and y are two variables from [0, 1), uniformly
  493. # distributed, then
  494. #
  495. # cos(2*pi*x)*sqrt(-2*log(1-y))
  496. # sin(2*pi*x)*sqrt(-2*log(1-y))
  497. #
  498. # are two *independent* variables with normal distribution
  499. # (mu = 0, sigma = 1).
  500. # (Lambert Meertens)
  501. # (corrected version; bug discovered by Mike Miller, fixed by LM)
  502. # Multithreading note: When two threads call this function
  503. # simultaneously, it is possible that they will receive the
  504. # same return value. The window is very small though. To
  505. # avoid this, you have to use a lock around all calls. (I
  506. # didn't want to slow this down in the serial case by using a
  507. # lock here.)
  508. random = self.random
  509. z = self.gauss_next
  510. self.gauss_next = None
  511. if z is None:
  512. x2pi = random() * TWOPI
  513. g2rad = _sqrt(-2.0 * _log(1.0 - random()))
  514. z = _cos(x2pi) * g2rad
  515. self.gauss_next = _sin(x2pi) * g2rad
  516. return mu + z*sigma
  517. ## -------------------- beta --------------------
  518. ## See
  519. ## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html
  520. ## for Ivan Frohne's insightful analysis of why the original implementation:
  521. ##
  522. ## def betavariate(self, alpha, beta):
  523. ## # Discrete Event Simulation in C, pp 87-88.
  524. ##
  525. ## y = self.expovariate(alpha)
  526. ## z = self.expovariate(1.0/beta)
  527. ## return z/(y+z)
  528. ##
  529. ## was dead wrong, and how it probably got that way.
  530. def betavariate(self, alpha, beta):
  531. """Beta distribution.
  532. Conditions on the parameters are alpha > 0 and beta > 0.
  533. Returned values range between 0 and 1.
  534. """
  535. # This version due to Janne Sinkkonen, and matches all the std
  536. # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
  537. y = self.gammavariate(alpha, 1.0)
  538. if y == 0:
  539. return 0.0
  540. else:
  541. return y / (y + self.gammavariate(beta, 1.0))
  542. ## -------------------- Pareto --------------------
  543. def paretovariate(self, alpha):
  544. """Pareto distribution. alpha is the shape parameter."""
  545. # Jain, pg. 495
  546. u = 1.0 - self.random()
  547. return 1.0 / u ** (1.0/alpha)
  548. ## -------------------- Weibull --------------------
  549. def weibullvariate(self, alpha, beta):
  550. """Weibull distribution.
  551. alpha is the scale parameter and beta is the shape parameter.
  552. """
  553. # Jain, pg. 499; bug fix courtesy Bill Arms
  554. u = 1.0 - self.random()
  555. return alpha * (-_log(u)) ** (1.0/beta)
  556. ## --------------- Operating System Random Source ------------------
  557. class SystemRandom(Random):
  558. """Alternate random number generator using sources provided
  559. by the operating system (such as /dev/urandom on Unix or
  560. CryptGenRandom on Windows).
  561. Not available on all systems (see os.urandom() for details).
  562. """
  563. def random(self):
  564. """Get the next random number in the range [0.0, 1.0)."""
  565. return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF
  566. def getrandbits(self, k):
  567. """getrandbits(k) -> x. Generates an int with k random bits."""
  568. if k <= 0:
  569. raise ValueError('number of bits must be greater than zero')
  570. numbytes = (k + 7) // 8 # bits / 8 and rounded up
  571. x = int.from_bytes(_urandom(numbytes), 'big')
  572. return x >> (numbytes * 8 - k) # trim excess bits
  573. def seed(self, *args, **kwds):
  574. "Stub method. Not used for a system random number generator."
  575. return None
  576. def _notimplemented(self, *args, **kwds):
  577. "Method should not be called for a system random number generator."
  578. raise NotImplementedError('System entropy source does not have state.')
  579. getstate = setstate = _notimplemented
  580. ## -------------------- test program --------------------
  581. def _test_generator(n, func, args):
  582. import time
  583. print(n, 'times', func.__name__)
  584. total = 0.0
  585. sqsum = 0.0
  586. smallest = 1e10
  587. largest = -1e10
  588. t0 = time.perf_counter()
  589. for i in range(n):
  590. x = func(*args)
  591. total += x
  592. sqsum = sqsum + x*x
  593. smallest = min(x, smallest)
  594. largest = max(x, largest)
  595. t1 = time.perf_counter()
  596. print(round(t1-t0, 3), 'sec,', end=' ')
  597. avg = total/n
  598. stddev = _sqrt(sqsum/n - avg*avg)
  599. print('avg %g, stddev %g, min %g, max %g\n' % \
  600. (avg, stddev, smallest, largest))
  601. def _test(N=2000):
  602. _test_generator(N, random, ())
  603. _test_generator(N, normalvariate, (0.0, 1.0))
  604. _test_generator(N, lognormvariate, (0.0, 1.0))
  605. _test_generator(N, vonmisesvariate, (0.0, 1.0))
  606. _test_generator(N, gammavariate, (0.01, 1.0))
  607. _test_generator(N, gammavariate, (0.1, 1.0))
  608. _test_generator(N, gammavariate, (0.1, 2.0))
  609. _test_generator(N, gammavariate, (0.5, 1.0))
  610. _test_generator(N, gammavariate, (0.9, 1.0))
  611. _test_generator(N, gammavariate, (1.0, 1.0))
  612. _test_generator(N, gammavariate, (2.0, 1.0))
  613. _test_generator(N, gammavariate, (20.0, 1.0))
  614. _test_generator(N, gammavariate, (200.0, 1.0))
  615. _test_generator(N, gauss, (0.0, 1.0))
  616. _test_generator(N, betavariate, (3.0, 3.0))
  617. _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0))
  618. # Create one instance, seeded from current time, and export its methods
  619. # as module-level functions. The functions share state across all uses
  620. #(both in the user's code and in the Python libraries), but that's fine
  621. # for most programs and is easier for the casual user than making them
  622. # instantiate their own Random() instance.
  623. _inst = Random()
  624. seed = _inst.seed
  625. random = _inst.random
  626. uniform = _inst.uniform
  627. triangular = _inst.triangular
  628. randint = _inst.randint
  629. choice = _inst.choice
  630. randrange = _inst.randrange
  631. sample = _inst.sample
  632. shuffle = _inst.shuffle
  633. choices = _inst.choices
  634. normalvariate = _inst.normalvariate
  635. lognormvariate = _inst.lognormvariate
  636. expovariate = _inst.expovariate
  637. vonmisesvariate = _inst.vonmisesvariate
  638. gammavariate = _inst.gammavariate
  639. gauss = _inst.gauss
  640. betavariate = _inst.betavariate
  641. paretovariate = _inst.paretovariate
  642. weibullvariate = _inst.weibullvariate
  643. getstate = _inst.getstate
  644. setstate = _inst.setstate
  645. getrandbits = _inst.getrandbits
  646. if hasattr(_os, "fork"):
  647. _os.register_at_fork(after_in_child=_inst.seed)
  648. if __name__ == '__main__':
  649. _test()