当前位置:   article > 正文

python3__标准库__random模块_uniform within range pick random element pick rand

uniform within range pick random element pick random sample pick weighted ra

1.random模块源代码

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

2.random模块的常见用法

  1. # ! /usr/bin/env python
  2. # coding:utf-8
  3. # python interpreter:3.6.2
  4. # author: admin_maxin
  5. import random
  6. # random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
  7. print(random.random())
  8. # random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。
  9. print(random.randint(1, 7))
  10. # 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
  11. print(random.randrange(1, 10))
  12. # random.randrange的函数原型为:random.randrange([start], stop[, step]),
  13. # 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
  14. # 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
  15. # random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
  16. # random.choice从序列中获取一个随机元素。
  17. # 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
  18. # 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
  19. # list, tuple, 字符串都属于sequence。
  20. print(random.choice('liukuni'))
  21. # 下面是使用choice的一些例子:
  22. print(random.choice("学习Python"))
  23. print(random.choice(["JGood", "is", "a", "handsome", "boy"]))
  24. print(random.choice(("Tuple", "List", "Dict")))
  25. # random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。
  26. print(random.sample([1, 2, 3, 4, 5], 3))

3.random模块的实际应用

简单的6位验证码实现

  1. import random
  2. checkcode = ""
  3. for i in range(6):
  4. current = random.randrange(0, 6)
  5. if current == i:
  6. tmp = chr(random.randint(65, 90))
  7. else:
  8. tmp = random.randint(0, 9)
  9. checkcode += str(tmp)
  10. print(checkcode)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/328002
推荐阅读
相关标签
  

闽ICP备14008679号