logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

random.py (33221B)


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