Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

random.py 27 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...