random.py 25 KB

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