random.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. """Random variable generators.
  2. bytes
  3. -----
  4. uniform bytes (values between 0 and 255)
  5. integers
  6. --------
  7. uniform within range
  8. sequences
  9. ---------
  10. pick random element
  11. pick random sample
  12. pick weighted random sample
  13. generate random permutation
  14. distributions on the real line:
  15. ------------------------------
  16. uniform
  17. triangular
  18. normal (Gaussian)
  19. lognormal
  20. negative exponential
  21. gamma
  22. beta
  23. pareto
  24. Weibull
  25. distributions on the circle (angles 0 to 2pi)
  26. ---------------------------------------------
  27. circular uniform
  28. von Mises
  29. discrete distributions
  30. ----------------------
  31. binomial
  32. General notes on the underlying Mersenne Twister core generator:
  33. * The period is 2**19937-1.
  34. * It is one of the most extensively tested generators in existence.
  35. * The random() method is implemented in C, executes in a single Python step,
  36. and is, therefore, threadsafe.
  37. """
  38. # Translated by Guido van Rossum from C source provided by
  39. # Adrian Baddeley. Adapted by Raymond Hettinger for use with
  40. # the Mersenne Twister and os.urandom() core generators.
  41. from warnings import warn as _warn
  42. from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
  43. from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
  44. from math import tau as TWOPI, floor as _floor, isfinite as _isfinite
  45. from math import lgamma as _lgamma, fabs as _fabs, log2 as _log2
  46. from os import urandom as _urandom
  47. from _collections_abc import Sequence as _Sequence
  48. from operator import index as _index
  49. from itertools import accumulate as _accumulate, repeat as _repeat
  50. from bisect import bisect as _bisect
  51. import os as _os
  52. import _random
  53. try:
  54. # hashlib is pretty heavy to load, try lean internal module first
  55. from _sha2 import sha512 as _sha512
  56. except ImportError:
  57. # fallback to official implementation
  58. from hashlib import sha512 as _sha512
  59. __all__ = [
  60. "Random",
  61. "SystemRandom",
  62. "betavariate",
  63. "binomialvariate",
  64. "choice",
  65. "choices",
  66. "expovariate",
  67. "gammavariate",
  68. "gauss",
  69. "getrandbits",
  70. "getstate",
  71. "lognormvariate",
  72. "normalvariate",
  73. "paretovariate",
  74. "randbytes",
  75. "randint",
  76. "random",
  77. "randrange",
  78. "sample",
  79. "seed",
  80. "setstate",
  81. "shuffle",
  82. "triangular",
  83. "uniform",
  84. "vonmisesvariate",
  85. "weibullvariate",
  86. ]
  87. NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0)
  88. LOG4 = _log(4.0)
  89. SG_MAGICCONST = 1.0 + _log(4.5)
  90. BPF = 53 # Number of bits in a float
  91. RECIP_BPF = 2 ** -BPF
  92. _ONE = 1
  93. class Random(_random.Random):
  94. """Random number generator base class used by bound module functions.
  95. Used to instantiate instances of Random to get generators that don't
  96. share state.
  97. Class Random can also be subclassed if you want to use a different basic
  98. generator of your own devising: in that case, override the following
  99. methods: random(), seed(), getstate(), and setstate().
  100. Optionally, implement a getrandbits() method so that randrange()
  101. can cover arbitrarily large ranges.
  102. """
  103. VERSION = 3 # used by getstate/setstate
  104. def __init__(self, x=None):
  105. """Initialize an instance.
  106. Optional argument x controls seeding, as for Random.seed().
  107. """
  108. self.seed(x)
  109. self.gauss_next = None
  110. def seed(self, a=None, version=2):
  111. """Initialize internal state from a seed.
  112. The only supported seed types are None, int, float,
  113. str, bytes, and bytearray.
  114. None or no argument seeds from current time or from an operating
  115. system specific randomness source if available.
  116. If *a* is an int, all bits are used.
  117. For version 2 (the default), all of the bits are used if *a* is a str,
  118. bytes, or bytearray. For version 1 (provided for reproducing random
  119. sequences from older versions of Python), the algorithm for str and
  120. bytes generates a narrower range of seeds.
  121. """
  122. if version == 1 and isinstance(a, (str, bytes)):
  123. a = a.decode('latin-1') if isinstance(a, bytes) else a
  124. x = ord(a[0]) << 7 if a else 0
  125. for c in map(ord, a):
  126. x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF
  127. x ^= len(a)
  128. a = -2 if x == -1 else x
  129. elif version == 2 and isinstance(a, (str, bytes, bytearray)):
  130. if isinstance(a, str):
  131. a = a.encode()
  132. a = int.from_bytes(a + _sha512(a).digest())
  133. elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)):
  134. raise TypeError('The only supported seed types are: None,\n'
  135. 'int, float, str, bytes, and bytearray.')
  136. super().seed(a)
  137. self.gauss_next = None
  138. def getstate(self):
  139. """Return internal state; can be passed to setstate() later."""
  140. return self.VERSION, super().getstate(), self.gauss_next
  141. def setstate(self, state):
  142. """Restore internal state from object returned by getstate()."""
  143. version = state[0]
  144. if version == 3:
  145. version, internalstate, self.gauss_next = state
  146. super().setstate(internalstate)
  147. elif version == 2:
  148. version, internalstate, self.gauss_next = state
  149. # In version 2, the state was saved as signed ints, which causes
  150. # inconsistencies between 32/64-bit systems. The state is
  151. # really unsigned 32-bit ints, so we convert negative ints from
  152. # version 2 to positive longs for version 3.
  153. try:
  154. internalstate = tuple(x % (2 ** 32) for x in internalstate)
  155. except ValueError as e:
  156. raise TypeError from e
  157. super().setstate(internalstate)
  158. else:
  159. raise ValueError("state with version %s passed to "
  160. "Random.setstate() of version %s" %
  161. (version, self.VERSION))
  162. ## -------------------------------------------------------
  163. ## ---- Methods below this point do not need to be overridden or extended
  164. ## ---- when subclassing for the purpose of using a different core generator.
  165. ## -------------------- pickle support -------------------
  166. # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
  167. # longer called; we leave it here because it has been here since random was
  168. # rewritten back in 2001 and why risk breaking something.
  169. def __getstate__(self): # for pickle
  170. return self.getstate()
  171. def __setstate__(self, state): # for pickle
  172. self.setstate(state)
  173. def __reduce__(self):
  174. return self.__class__, (), self.getstate()
  175. ## ---- internal support method for evenly distributed integers ----
  176. def __init_subclass__(cls, /, **kwargs):
  177. """Control how subclasses generate random integers.
  178. The algorithm a subclass can use depends on the random() and/or
  179. getrandbits() implementation available to it and determines
  180. whether it can generate random integers from arbitrarily large
  181. ranges.
  182. """
  183. for c in cls.__mro__:
  184. if '_randbelow' in c.__dict__:
  185. # just inherit it
  186. break
  187. if 'getrandbits' in c.__dict__:
  188. cls._randbelow = cls._randbelow_with_getrandbits
  189. break
  190. if 'random' in c.__dict__:
  191. cls._randbelow = cls._randbelow_without_getrandbits
  192. break
  193. def _randbelow_with_getrandbits(self, n):
  194. "Return a random int in the range [0,n). Defined for n > 0."
  195. getrandbits = self.getrandbits
  196. k = n.bit_length()
  197. r = getrandbits(k) # 0 <= r < 2**k
  198. while r >= n:
  199. r = getrandbits(k)
  200. return r
  201. def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF):
  202. """Return a random int in the range [0,n). Defined for n > 0.
  203. The implementation does not use getrandbits, but only random.
  204. """
  205. random = self.random
  206. if n >= maxsize:
  207. _warn("Underlying random() generator does not supply \n"
  208. "enough bits to choose from a population range this large.\n"
  209. "To remove the range limitation, add a getrandbits() method.")
  210. return _floor(random() * n)
  211. rem = maxsize % n
  212. limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
  213. r = random()
  214. while r >= limit:
  215. r = random()
  216. return _floor(r * maxsize) % n
  217. _randbelow = _randbelow_with_getrandbits
  218. ## --------------------------------------------------------
  219. ## ---- Methods below this point generate custom distributions
  220. ## ---- based on the methods defined above. They do not
  221. ## ---- directly touch the underlying generator and only
  222. ## ---- access randomness through the methods: random(),
  223. ## ---- getrandbits(), or _randbelow().
  224. ## -------------------- bytes methods ---------------------
  225. def randbytes(self, n):
  226. """Generate n random bytes."""
  227. return self.getrandbits(n * 8).to_bytes(n, 'little')
  228. ## -------------------- integer methods -------------------
  229. def randrange(self, start, stop=None, step=_ONE):
  230. """Choose a random item from range(stop) or range(start, stop[, step]).
  231. Roughly equivalent to ``choice(range(start, stop, step))`` but
  232. supports arbitrarily large ranges and is optimized for common cases.
  233. """
  234. # This code is a bit messy to make it fast for the
  235. # common case while still doing adequate error checking.
  236. istart = _index(start)
  237. if stop is None:
  238. # We don't check for "step != 1" because it hasn't been
  239. # type checked and converted to an integer yet.
  240. if step is not _ONE:
  241. raise TypeError("Missing a non-None stop argument")
  242. if istart > 0:
  243. return self._randbelow(istart)
  244. raise ValueError("empty range for randrange()")
  245. # Stop argument supplied.
  246. istop = _index(stop)
  247. width = istop - istart
  248. istep = _index(step)
  249. # Fast path.
  250. if istep == 1:
  251. if width > 0:
  252. return istart + self._randbelow(width)
  253. raise ValueError(f"empty range in randrange({start}, {stop})")
  254. # Non-unit step argument supplied.
  255. if istep > 0:
  256. n = (width + istep - 1) // istep
  257. elif istep < 0:
  258. n = (width + istep + 1) // istep
  259. else:
  260. raise ValueError("zero step for randrange()")
  261. if n <= 0:
  262. raise ValueError(f"empty range in randrange({start}, {stop}, {step})")
  263. return istart + istep * self._randbelow(n)
  264. def randint(self, a, b):
  265. """Return random integer in range [a, b], including both end points.
  266. """
  267. return self.randrange(a, b+1)
  268. ## -------------------- sequence methods -------------------
  269. def choice(self, seq):
  270. """Choose a random element from a non-empty sequence."""
  271. # As an accommodation for NumPy, we don't use "if not seq"
  272. # because bool(numpy.array()) raises a ValueError.
  273. if not len(seq):
  274. raise IndexError('Cannot choose from an empty sequence')
  275. return seq[self._randbelow(len(seq))]
  276. def shuffle(self, x):
  277. """Shuffle list x in place, and return None."""
  278. randbelow = self._randbelow
  279. for i in reversed(range(1, len(x))):
  280. # pick an element in x[:i+1] with which to exchange x[i]
  281. j = randbelow(i + 1)
  282. x[i], x[j] = x[j], x[i]
  283. def sample(self, population, k, *, counts=None):
  284. """Chooses k unique random elements from a population sequence.
  285. Returns a new list containing elements from the population while
  286. leaving the original population unchanged. The resulting list is
  287. in selection order so that all sub-slices will also be valid random
  288. samples. This allows raffle winners (the sample) to be partitioned
  289. into grand prize and second place winners (the subslices).
  290. Members of the population need not be hashable or unique. If the
  291. population contains repeats, then each occurrence is a possible
  292. selection in the sample.
  293. Repeated elements can be specified one at a time or with the optional
  294. counts parameter. For example:
  295. sample(['red', 'blue'], counts=[4, 2], k=5)
  296. is equivalent to:
  297. sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
  298. To choose a sample from a range of integers, use range() for the
  299. population argument. This is especially fast and space efficient
  300. for sampling from a large population:
  301. sample(range(10000000), 60)
  302. """
  303. # Sampling without replacement entails tracking either potential
  304. # selections (the pool) in a list or previous selections in a set.
  305. # When the number of selections is small compared to the
  306. # population, then tracking selections is efficient, requiring
  307. # only a small set and an occasional reselection. For
  308. # a larger number of selections, the pool tracking method is
  309. # preferred since the list takes less space than the
  310. # set and it doesn't suffer from frequent reselections.
  311. # The number of calls to _randbelow() is kept at or near k, the
  312. # theoretical minimum. This is important because running time
  313. # is dominated by _randbelow() and because it extracts the
  314. # least entropy from the underlying random number generators.
  315. # Memory requirements are kept to the smaller of a k-length
  316. # set or an n-length list.
  317. # There are other sampling algorithms that do not require
  318. # auxiliary memory, but they were rejected because they made
  319. # too many calls to _randbelow(), making them slower and
  320. # causing them to eat more entropy than necessary.
  321. if not isinstance(population, _Sequence):
  322. raise TypeError("Population must be a sequence. "
  323. "For dicts or sets, use sorted(d).")
  324. n = len(population)
  325. if counts is not None:
  326. cum_counts = list(_accumulate(counts))
  327. if len(cum_counts) != n:
  328. raise ValueError('The number of counts does not match the population')
  329. total = cum_counts.pop()
  330. if not isinstance(total, int):
  331. raise TypeError('Counts must be integers')
  332. if total <= 0:
  333. raise ValueError('Total of counts must be greater than zero')
  334. selections = self.sample(range(total), k=k)
  335. bisect = _bisect
  336. return [population[bisect(cum_counts, s)] for s in selections]
  337. randbelow = self._randbelow
  338. if not 0 <= k <= n:
  339. raise ValueError("Sample larger than population or is negative")
  340. result = [None] * k
  341. setsize = 21 # size of a small set minus size of an empty list
  342. if k > 5:
  343. setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
  344. if n <= setsize:
  345. # An n-length list is smaller than a k-length set.
  346. # Invariant: non-selected at pool[0 : n-i]
  347. pool = list(population)
  348. for i in range(k):
  349. j = randbelow(n - i)
  350. result[i] = pool[j]
  351. pool[j] = pool[n - i - 1] # move non-selected item into vacancy
  352. else:
  353. selected = set()
  354. selected_add = selected.add
  355. for i in range(k):
  356. j = randbelow(n)
  357. while j in selected:
  358. j = randbelow(n)
  359. selected_add(j)
  360. result[i] = population[j]
  361. return result
  362. def choices(self, population, weights=None, *, cum_weights=None, k=1):
  363. """Return a k sized list of population elements chosen with replacement.
  364. If the relative weights or cumulative weights are not specified,
  365. the selections are made with equal probability.
  366. """
  367. random = self.random
  368. n = len(population)
  369. if cum_weights is None:
  370. if weights is None:
  371. floor = _floor
  372. n += 0.0 # convert to float for a small speed improvement
  373. return [population[floor(random() * n)] for i in _repeat(None, k)]
  374. try:
  375. cum_weights = list(_accumulate(weights))
  376. except TypeError:
  377. if not isinstance(weights, int):
  378. raise
  379. k = weights
  380. raise TypeError(
  381. f'The number of choices must be a keyword argument: {k=}'
  382. ) from None
  383. elif weights is not None:
  384. raise TypeError('Cannot specify both weights and cumulative weights')
  385. if len(cum_weights) != n:
  386. raise ValueError('The number of weights does not match the population')
  387. total = cum_weights[-1] + 0.0 # convert to float
  388. if total <= 0.0:
  389. raise ValueError('Total of weights must be greater than zero')
  390. if not _isfinite(total):
  391. raise ValueError('Total of weights must be finite')
  392. bisect = _bisect
  393. hi = n - 1
  394. return [population[bisect(cum_weights, random() * total, 0, hi)]
  395. for i in _repeat(None, k)]
  396. ## -------------------- real-valued distributions -------------------
  397. def uniform(self, a, b):
  398. """Get a random number in the range [a, b) or [a, b] depending on rounding.
  399. The mean (expected value) and variance of the random variable are:
  400. E[X] = (a + b) / 2
  401. Var[X] = (b - a) ** 2 / 12
  402. """
  403. return a + (b - a) * self.random()
  404. def triangular(self, low=0.0, high=1.0, mode=None):
  405. """Triangular distribution.
  406. Continuous distribution bounded by given lower and upper limits,
  407. and having a given mode value in-between.
  408. http://en.wikipedia.org/wiki/Triangular_distribution
  409. The mean (expected value) and variance of the random variable are:
  410. E[X] = (low + high + mode) / 3
  411. Var[X] = (low**2 + high**2 + mode**2 - low*high - low*mode - high*mode) / 18
  412. """
  413. u = self.random()
  414. try:
  415. c = 0.5 if mode is None else (mode - low) / (high - low)
  416. except ZeroDivisionError:
  417. return low
  418. if u > c:
  419. u = 1.0 - u
  420. c = 1.0 - c
  421. low, high = high, low
  422. return low + (high - low) * _sqrt(u * c)
  423. def normalvariate(self, mu=0.0, sigma=1.0):
  424. """Normal distribution.
  425. mu is the mean, and sigma is the standard deviation.
  426. """
  427. # Uses Kinderman and Monahan method. Reference: Kinderman,
  428. # A.J. and Monahan, J.F., "Computer generation of random
  429. # variables using the ratio of uniform deviates", ACM Trans
  430. # Math Software, 3, (1977), pp257-260.
  431. random = self.random
  432. while True:
  433. u1 = random()
  434. u2 = 1.0 - random()
  435. z = NV_MAGICCONST * (u1 - 0.5) / u2
  436. zz = z * z / 4.0
  437. if zz <= -_log(u2):
  438. break
  439. return mu + z * sigma
  440. def gauss(self, mu=0.0, sigma=1.0):
  441. """Gaussian distribution.
  442. mu is the mean, and sigma is the standard deviation. This is
  443. slightly faster than the normalvariate() function.
  444. Not thread-safe without a lock around calls.
  445. """
  446. # When x and y are two variables from [0, 1), uniformly
  447. # distributed, then
  448. #
  449. # cos(2*pi*x)*sqrt(-2*log(1-y))
  450. # sin(2*pi*x)*sqrt(-2*log(1-y))
  451. #
  452. # are two *independent* variables with normal distribution
  453. # (mu = 0, sigma = 1).
  454. # (Lambert Meertens)
  455. # (corrected version; bug discovered by Mike Miller, fixed by LM)
  456. # Multithreading note: When two threads call this function
  457. # simultaneously, it is possible that they will receive the
  458. # same return value. The window is very small though. To
  459. # avoid this, you have to use a lock around all calls. (I
  460. # didn't want to slow this down in the serial case by using a
  461. # lock here.)
  462. random = self.random
  463. z = self.gauss_next
  464. self.gauss_next = None
  465. if z is None:
  466. x2pi = random() * TWOPI
  467. g2rad = _sqrt(-2.0 * _log(1.0 - random()))
  468. z = _cos(x2pi) * g2rad
  469. self.gauss_next = _sin(x2pi) * g2rad
  470. return mu + z * sigma
  471. def lognormvariate(self, mu, sigma):
  472. """Log normal distribution.
  473. If you take the natural logarithm of this distribution, you'll get a
  474. normal distribution with mean mu and standard deviation sigma.
  475. mu can have any value, and sigma must be greater than zero.
  476. """
  477. return _exp(self.normalvariate(mu, sigma))
  478. def expovariate(self, lambd=1.0):
  479. """Exponential distribution.
  480. lambd is 1.0 divided by the desired mean. It should be
  481. nonzero. (The parameter would be called "lambda", but that is
  482. a reserved word in Python.) Returned values range from 0 to
  483. positive infinity if lambd is positive, and from negative
  484. infinity to 0 if lambd is negative.
  485. The mean (expected value) and variance of the random variable are:
  486. E[X] = 1 / lambd
  487. Var[X] = 1 / lambd ** 2
  488. """
  489. # we use 1-random() instead of random() to preclude the
  490. # possibility of taking the log of zero.
  491. return -_log(1.0 - self.random()) / lambd
  492. def vonmisesvariate(self, mu, kappa):
  493. """Circular data distribution.
  494. mu is the mean angle, expressed in radians between 0 and 2*pi, and
  495. kappa is the concentration parameter, which must be greater than or
  496. equal to zero. If kappa is equal to zero, this distribution reduces
  497. to a uniform random angle over the range 0 to 2*pi.
  498. """
  499. # Based upon an algorithm published in: Fisher, N.I.,
  500. # "Statistical Analysis of Circular Data", Cambridge
  501. # University Press, 1993.
  502. # Thanks to Magnus Kessler for a correction to the
  503. # implementation of step 4.
  504. random = self.random
  505. if kappa <= 1e-6:
  506. return TWOPI * random()
  507. s = 0.5 / kappa
  508. r = s + _sqrt(1.0 + s * s)
  509. while True:
  510. u1 = random()
  511. z = _cos(_pi * u1)
  512. d = z / (r + z)
  513. u2 = random()
  514. if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d):
  515. break
  516. q = 1.0 / r
  517. f = (q + z) / (1.0 + q * z)
  518. u3 = random()
  519. if u3 > 0.5:
  520. theta = (mu + _acos(f)) % TWOPI
  521. else:
  522. theta = (mu - _acos(f)) % TWOPI
  523. return theta
  524. def gammavariate(self, alpha, beta):
  525. """Gamma distribution. Not the gamma function!
  526. Conditions on the parameters are alpha > 0 and beta > 0.
  527. The probability distribution function is:
  528. x ** (alpha - 1) * math.exp(-x / beta)
  529. pdf(x) = --------------------------------------
  530. math.gamma(alpha) * beta ** alpha
  531. The mean (expected value) and variance of the random variable are:
  532. E[X] = alpha * beta
  533. Var[X] = alpha * beta ** 2
  534. """
  535. # Warning: a few older sources define the gamma distribution in terms
  536. # of alpha > -1.0
  537. if alpha <= 0.0 or beta <= 0.0:
  538. raise ValueError('gammavariate: alpha and beta must be > 0.0')
  539. random = self.random
  540. if alpha > 1.0:
  541. # Uses R.C.H. Cheng, "The generation of Gamma
  542. # variables with non-integral shape parameters",
  543. # Applied Statistics, (1977), 26, No. 1, p71-74
  544. ainv = _sqrt(2.0 * alpha - 1.0)
  545. bbb = alpha - LOG4
  546. ccc = alpha + ainv
  547. while True:
  548. u1 = random()
  549. if not 1e-7 < u1 < 0.9999999:
  550. continue
  551. u2 = 1.0 - random()
  552. v = _log(u1 / (1.0 - u1)) / ainv
  553. x = alpha * _exp(v)
  554. z = u1 * u1 * u2
  555. r = bbb + ccc * v - x
  556. if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= _log(z):
  557. return x * beta
  558. elif alpha == 1.0:
  559. # expovariate(1/beta)
  560. return -_log(1.0 - random()) * beta
  561. else:
  562. # alpha is between 0 and 1 (exclusive)
  563. # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
  564. while True:
  565. u = random()
  566. b = (_e + alpha) / _e
  567. p = b * u
  568. if p <= 1.0:
  569. x = p ** (1.0 / alpha)
  570. else:
  571. x = -_log((b - p) / alpha)
  572. u1 = random()
  573. if p > 1.0:
  574. if u1 <= x ** (alpha - 1.0):
  575. break
  576. elif u1 <= _exp(-x):
  577. break
  578. return x * beta
  579. def betavariate(self, alpha, beta):
  580. """Beta distribution.
  581. Conditions on the parameters are alpha > 0 and beta > 0.
  582. Returned values range between 0 and 1.
  583. The mean (expected value) and variance of the random variable are:
  584. E[X] = alpha / (alpha + beta)
  585. Var[X] = alpha * beta / ((alpha + beta)**2 * (alpha + beta + 1))
  586. """
  587. ## See
  588. ## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html
  589. ## for Ivan Frohne's insightful analysis of why the original implementation:
  590. ##
  591. ## def betavariate(self, alpha, beta):
  592. ## # Discrete Event Simulation in C, pp 87-88.
  593. ##
  594. ## y = self.expovariate(alpha)
  595. ## z = self.expovariate(1.0/beta)
  596. ## return z/(y+z)
  597. ##
  598. ## was dead wrong, and how it probably got that way.
  599. # This version due to Janne Sinkkonen, and matches all the std
  600. # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
  601. y = self.gammavariate(alpha, 1.0)
  602. if y:
  603. return y / (y + self.gammavariate(beta, 1.0))
  604. return 0.0
  605. def paretovariate(self, alpha):
  606. """Pareto distribution. alpha is the shape parameter."""
  607. # Jain, pg. 495
  608. u = 1.0 - self.random()
  609. return u ** (-1.0 / alpha)
  610. def weibullvariate(self, alpha, beta):
  611. """Weibull distribution.
  612. alpha is the scale parameter and beta is the shape parameter.
  613. """
  614. # Jain, pg. 499; bug fix courtesy Bill Arms
  615. u = 1.0 - self.random()
  616. return alpha * (-_log(u)) ** (1.0 / beta)
  617. ## -------------------- discrete distributions ---------------------
  618. def binomialvariate(self, n=1, p=0.5):
  619. """Binomial random variable.
  620. Gives the number of successes for *n* independent trials
  621. with the probability of success in each trial being *p*:
  622. sum(random() < p for i in range(n))
  623. Returns an integer in the range: 0 <= X <= n
  624. The mean (expected value) and variance of the random variable are:
  625. E[X] = n * p
  626. Var[x] = n * p * (1 - p)
  627. """
  628. # Error check inputs and handle edge cases
  629. if n < 0:
  630. raise ValueError("n must be non-negative")
  631. if p <= 0.0 or p >= 1.0:
  632. if p == 0.0:
  633. return 0
  634. if p == 1.0:
  635. return n
  636. raise ValueError("p must be in the range 0.0 <= p <= 1.0")
  637. random = self.random
  638. # Fast path for a common case
  639. if n == 1:
  640. return _index(random() < p)
  641. # Exploit symmetry to establish: p <= 0.5
  642. if p > 0.5:
  643. return n - self.binomialvariate(n, 1.0 - p)
  644. if n * p < 10.0:
  645. # BG: Geometric method by Devroye with running time of O(np).
  646. # https://dl.acm.org/doi/pdf/10.1145/42372.42381
  647. x = y = 0
  648. c = _log2(1.0 - p)
  649. if not c:
  650. return x
  651. while True:
  652. y += _floor(_log2(random()) / c) + 1
  653. if y > n:
  654. return x
  655. x += 1
  656. # BTRS: Transformed rejection with squeeze method by Wolfgang Hörmann
  657. # https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.47.8407&rep=rep1&type=pdf
  658. assert n*p >= 10.0 and p <= 0.5
  659. setup_complete = False
  660. spq = _sqrt(n * p * (1.0 - p)) # Standard deviation of the distribution
  661. b = 1.15 + 2.53 * spq
  662. a = -0.0873 + 0.0248 * b + 0.01 * p
  663. c = n * p + 0.5
  664. vr = 0.92 - 4.2 / b
  665. while True:
  666. u = random()
  667. u -= 0.5
  668. us = 0.5 - _fabs(u)
  669. k = _floor((2.0 * a / us + b) * u + c)
  670. if k < 0 or k > n:
  671. continue
  672. # The early-out "squeeze" test substantially reduces
  673. # the number of acceptance condition evaluations.
  674. v = random()
  675. if us >= 0.07 and v <= vr:
  676. return k
  677. # Acceptance-rejection test.
  678. # Note, the original paper erroneously omits the call to log(v)
  679. # when comparing to the log of the rescaled binomial distribution.
  680. if not setup_complete:
  681. alpha = (2.83 + 5.1 / b) * spq
  682. lpq = _log(p / (1.0 - p))
  683. m = _floor((n + 1) * p) # Mode of the distribution
  684. h = _lgamma(m + 1) + _lgamma(n - m + 1)
  685. setup_complete = True # Only needs to be done once
  686. v *= alpha / (a / (us * us) + b)
  687. if _log(v) <= h - _lgamma(k + 1) - _lgamma(n - k + 1) + (k - m) * lpq:
  688. return k
  689. ## ------------------------------------------------------------------
  690. ## --------------- Operating System Random Source ------------------
  691. class SystemRandom(Random):
  692. """Alternate random number generator using sources provided
  693. by the operating system (such as /dev/urandom on Unix or
  694. CryptGenRandom on Windows).
  695. Not available on all systems (see os.urandom() for details).
  696. """
  697. def random(self):
  698. """Get the next random number in the range 0.0 <= X < 1.0."""
  699. return (int.from_bytes(_urandom(7)) >> 3) * RECIP_BPF
  700. def getrandbits(self, k):
  701. """getrandbits(k) -> x. Generates an int with k random bits."""
  702. if k < 0:
  703. raise ValueError('number of bits must be non-negative')
  704. numbytes = (k + 7) // 8 # bits / 8 and rounded up
  705. x = int.from_bytes(_urandom(numbytes))
  706. return x >> (numbytes * 8 - k) # trim excess bits
  707. def randbytes(self, n):
  708. """Generate n random bytes."""
  709. # os.urandom(n) fails with ValueError for n < 0
  710. # and returns an empty bytes string for n == 0.
  711. return _urandom(n)
  712. def seed(self, *args, **kwds):
  713. "Stub method. Not used for a system random number generator."
  714. return None
  715. def _notimplemented(self, *args, **kwds):
  716. "Method should not be called for a system random number generator."
  717. raise NotImplementedError('System entropy source does not have state.')
  718. getstate = setstate = _notimplemented
  719. # ----------------------------------------------------------------------
  720. # Create one instance, seeded from current time, and export its methods
  721. # as module-level functions. The functions share state across all uses
  722. # (both in the user's code and in the Python libraries), but that's fine
  723. # for most programs and is easier for the casual user than making them
  724. # instantiate their own Random() instance.
  725. _inst = Random()
  726. seed = _inst.seed
  727. random = _inst.random
  728. uniform = _inst.uniform
  729. triangular = _inst.triangular
  730. randint = _inst.randint
  731. choice = _inst.choice
  732. randrange = _inst.randrange
  733. sample = _inst.sample
  734. shuffle = _inst.shuffle
  735. choices = _inst.choices
  736. normalvariate = _inst.normalvariate
  737. lognormvariate = _inst.lognormvariate
  738. expovariate = _inst.expovariate
  739. vonmisesvariate = _inst.vonmisesvariate
  740. gammavariate = _inst.gammavariate
  741. gauss = _inst.gauss
  742. betavariate = _inst.betavariate
  743. binomialvariate = _inst.binomialvariate
  744. paretovariate = _inst.paretovariate
  745. weibullvariate = _inst.weibullvariate
  746. getstate = _inst.getstate
  747. setstate = _inst.setstate
  748. getrandbits = _inst.getrandbits
  749. randbytes = _inst.randbytes
  750. ## ------------------------------------------------------
  751. ## ----------------- test program -----------------------
  752. def _test_generator(n, func, args):
  753. from statistics import stdev, fmean as mean
  754. from time import perf_counter
  755. t0 = perf_counter()
  756. data = [func(*args) for i in _repeat(None, n)]
  757. t1 = perf_counter()
  758. xbar = mean(data)
  759. sigma = stdev(data, xbar)
  760. low = min(data)
  761. high = max(data)
  762. print(f'{t1 - t0:.3f} sec, {n} times {func.__name__}{args!r}')
  763. print('avg %g, stddev %g, min %g, max %g\n' % (xbar, sigma, low, high))
  764. def _test(N=10_000):
  765. _test_generator(N, random, ())
  766. _test_generator(N, normalvariate, (0.0, 1.0))
  767. _test_generator(N, lognormvariate, (0.0, 1.0))
  768. _test_generator(N, vonmisesvariate, (0.0, 1.0))
  769. _test_generator(N, binomialvariate, (15, 0.60))
  770. _test_generator(N, binomialvariate, (100, 0.75))
  771. _test_generator(N, gammavariate, (0.01, 1.0))
  772. _test_generator(N, gammavariate, (0.1, 1.0))
  773. _test_generator(N, gammavariate, (0.1, 2.0))
  774. _test_generator(N, gammavariate, (0.5, 1.0))
  775. _test_generator(N, gammavariate, (0.9, 1.0))
  776. _test_generator(N, gammavariate, (1.0, 1.0))
  777. _test_generator(N, gammavariate, (2.0, 1.0))
  778. _test_generator(N, gammavariate, (20.0, 1.0))
  779. _test_generator(N, gammavariate, (200.0, 1.0))
  780. _test_generator(N, gauss, (0.0, 1.0))
  781. _test_generator(N, betavariate, (3.0, 3.0))
  782. _test_generator(N, triangular, (0.0, 1.0, 1.0 / 3.0))
  783. ## ------------------------------------------------------
  784. ## ------------------ fork support ---------------------
  785. if hasattr(_os, "fork"):
  786. _os.register_at_fork(after_in_child=_inst.seed)
  787. if __name__ == '__main__':
  788. _test()