random.py 31 KB

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