Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python3....
File: random.py
"""Random variable generators.
[0] Fix | Delete
[1] Fix | Delete
integers
[2] Fix | Delete
--------
[3] Fix | Delete
uniform within range
[4] Fix | Delete
[5] Fix | Delete
sequences
[6] Fix | Delete
---------
[7] Fix | Delete
pick random element
[8] Fix | Delete
pick random sample
[9] Fix | Delete
pick weighted random sample
[10] Fix | Delete
generate random permutation
[11] Fix | Delete
[12] Fix | Delete
distributions on the real line:
[13] Fix | Delete
------------------------------
[14] Fix | Delete
uniform
[15] Fix | Delete
triangular
[16] Fix | Delete
normal (Gaussian)
[17] Fix | Delete
lognormal
[18] Fix | Delete
negative exponential
[19] Fix | Delete
gamma
[20] Fix | Delete
beta
[21] Fix | Delete
pareto
[22] Fix | Delete
Weibull
[23] Fix | Delete
[24] Fix | Delete
distributions on the circle (angles 0 to 2pi)
[25] Fix | Delete
---------------------------------------------
[26] Fix | Delete
circular uniform
[27] Fix | Delete
von Mises
[28] Fix | Delete
[29] Fix | Delete
General notes on the underlying Mersenne Twister core generator:
[30] Fix | Delete
[31] Fix | Delete
* The period is 2**19937-1.
[32] Fix | Delete
* It is one of the most extensively tested generators in existence.
[33] Fix | Delete
* The random() method is implemented in C, executes in a single Python step,
[34] Fix | Delete
and is, therefore, threadsafe.
[35] Fix | Delete
[36] Fix | Delete
"""
[37] Fix | Delete
[38] Fix | Delete
from warnings import warn as _warn
[39] Fix | Delete
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
[40] Fix | Delete
from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
[41] Fix | Delete
from os import urandom as _urandom
[42] Fix | Delete
from _collections_abc import Set as _Set, Sequence as _Sequence
[43] Fix | Delete
from itertools import accumulate as _accumulate, repeat as _repeat
[44] Fix | Delete
from bisect import bisect as _bisect
[45] Fix | Delete
import os as _os
[46] Fix | Delete
[47] Fix | Delete
try:
[48] Fix | Delete
# hashlib is pretty heavy to load, try lean internal module first
[49] Fix | Delete
from _sha512 import sha512 as _sha512
[50] Fix | Delete
except ImportError:
[51] Fix | Delete
# fallback to official implementation
[52] Fix | Delete
from hashlib import sha512 as _sha512
[53] Fix | Delete
[54] Fix | Delete
[55] Fix | Delete
__all__ = ["Random","seed","random","uniform","randint","choice","sample",
[56] Fix | Delete
"randrange","shuffle","normalvariate","lognormvariate",
[57] Fix | Delete
"expovariate","vonmisesvariate","gammavariate","triangular",
[58] Fix | Delete
"gauss","betavariate","paretovariate","weibullvariate",
[59] Fix | Delete
"getstate","setstate", "getrandbits", "choices",
[60] Fix | Delete
"SystemRandom"]
[61] Fix | Delete
[62] Fix | Delete
NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
[63] Fix | Delete
TWOPI = 2.0*_pi
[64] Fix | Delete
LOG4 = _log(4.0)
[65] Fix | Delete
SG_MAGICCONST = 1.0 + _log(4.5)
[66] Fix | Delete
BPF = 53 # Number of bits in a float
[67] Fix | Delete
RECIP_BPF = 2**-BPF
[68] Fix | Delete
[69] Fix | Delete
[70] Fix | Delete
# Translated by Guido van Rossum from C source provided by
[71] Fix | Delete
# Adrian Baddeley. Adapted by Raymond Hettinger for use with
[72] Fix | Delete
# the Mersenne Twister and os.urandom() core generators.
[73] Fix | Delete
[74] Fix | Delete
import _random
[75] Fix | Delete
[76] Fix | Delete
class Random(_random.Random):
[77] Fix | Delete
"""Random number generator base class used by bound module functions.
[78] Fix | Delete
[79] Fix | Delete
Used to instantiate instances of Random to get generators that don't
[80] Fix | Delete
share state.
[81] Fix | Delete
[82] Fix | Delete
Class Random can also be subclassed if you want to use a different basic
[83] Fix | Delete
generator of your own devising: in that case, override the following
[84] Fix | Delete
methods: random(), seed(), getstate(), and setstate().
[85] Fix | Delete
Optionally, implement a getrandbits() method so that randrange()
[86] Fix | Delete
can cover arbitrarily large ranges.
[87] Fix | Delete
[88] Fix | Delete
"""
[89] Fix | Delete
[90] Fix | Delete
VERSION = 3 # used by getstate/setstate
[91] Fix | Delete
[92] Fix | Delete
def __init__(self, x=None):
[93] Fix | Delete
"""Initialize an instance.
[94] Fix | Delete
[95] Fix | Delete
Optional argument x controls seeding, as for Random.seed().
[96] Fix | Delete
"""
[97] Fix | Delete
[98] Fix | Delete
self.seed(x)
[99] Fix | Delete
self.gauss_next = None
[100] Fix | Delete
[101] Fix | Delete
def __init_subclass__(cls, /, **kwargs):
[102] Fix | Delete
"""Control how subclasses generate random integers.
[103] Fix | Delete
[104] Fix | Delete
The algorithm a subclass can use depends on the random() and/or
[105] Fix | Delete
getrandbits() implementation available to it and determines
[106] Fix | Delete
whether it can generate random integers from arbitrarily large
[107] Fix | Delete
ranges.
[108] Fix | Delete
"""
[109] Fix | Delete
[110] Fix | Delete
for c in cls.__mro__:
[111] Fix | Delete
if '_randbelow' in c.__dict__:
[112] Fix | Delete
# just inherit it
[113] Fix | Delete
break
[114] Fix | Delete
if 'getrandbits' in c.__dict__:
[115] Fix | Delete
cls._randbelow = cls._randbelow_with_getrandbits
[116] Fix | Delete
break
[117] Fix | Delete
if 'random' in c.__dict__:
[118] Fix | Delete
cls._randbelow = cls._randbelow_without_getrandbits
[119] Fix | Delete
break
[120] Fix | Delete
[121] Fix | Delete
def seed(self, a=None, version=2):
[122] Fix | Delete
"""Initialize internal state from hashable object.
[123] Fix | Delete
[124] Fix | Delete
None or no argument seeds from current time or from an operating
[125] Fix | Delete
system specific randomness source if available.
[126] Fix | Delete
[127] Fix | Delete
If *a* is an int, all bits are used.
[128] Fix | Delete
[129] Fix | Delete
For version 2 (the default), all of the bits are used if *a* is a str,
[130] Fix | Delete
bytes, or bytearray. For version 1 (provided for reproducing random
[131] Fix | Delete
sequences from older versions of Python), the algorithm for str and
[132] Fix | Delete
bytes generates a narrower range of seeds.
[133] Fix | Delete
[134] Fix | Delete
"""
[135] Fix | Delete
[136] Fix | Delete
if version == 1 and isinstance(a, (str, bytes)):
[137] Fix | Delete
a = a.decode('latin-1') if isinstance(a, bytes) else a
[138] Fix | Delete
x = ord(a[0]) << 7 if a else 0
[139] Fix | Delete
for c in map(ord, a):
[140] Fix | Delete
x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF
[141] Fix | Delete
x ^= len(a)
[142] Fix | Delete
a = -2 if x == -1 else x
[143] Fix | Delete
[144] Fix | Delete
if version == 2 and isinstance(a, (str, bytes, bytearray)):
[145] Fix | Delete
if isinstance(a, str):
[146] Fix | Delete
a = a.encode()
[147] Fix | Delete
a += _sha512(a).digest()
[148] Fix | Delete
a = int.from_bytes(a, 'big')
[149] Fix | Delete
[150] Fix | Delete
super().seed(a)
[151] Fix | Delete
self.gauss_next = None
[152] Fix | Delete
[153] Fix | Delete
def getstate(self):
[154] Fix | Delete
"""Return internal state; can be passed to setstate() later."""
[155] Fix | Delete
return self.VERSION, super().getstate(), self.gauss_next
[156] Fix | Delete
[157] Fix | Delete
def setstate(self, state):
[158] Fix | Delete
"""Restore internal state from object returned by getstate()."""
[159] Fix | Delete
version = state[0]
[160] Fix | Delete
if version == 3:
[161] Fix | Delete
version, internalstate, self.gauss_next = state
[162] Fix | Delete
super().setstate(internalstate)
[163] Fix | Delete
elif version == 2:
[164] Fix | Delete
version, internalstate, self.gauss_next = state
[165] Fix | Delete
# In version 2, the state was saved as signed ints, which causes
[166] Fix | Delete
# inconsistencies between 32/64-bit systems. The state is
[167] Fix | Delete
# really unsigned 32-bit ints, so we convert negative ints from
[168] Fix | Delete
# version 2 to positive longs for version 3.
[169] Fix | Delete
try:
[170] Fix | Delete
internalstate = tuple(x % (2**32) for x in internalstate)
[171] Fix | Delete
except ValueError as e:
[172] Fix | Delete
raise TypeError from e
[173] Fix | Delete
super().setstate(internalstate)
[174] Fix | Delete
else:
[175] Fix | Delete
raise ValueError("state with version %s passed to "
[176] Fix | Delete
"Random.setstate() of version %s" %
[177] Fix | Delete
(version, self.VERSION))
[178] Fix | Delete
[179] Fix | Delete
## ---- Methods below this point do not need to be overridden when
[180] Fix | Delete
## ---- subclassing for the purpose of using a different core generator.
[181] Fix | Delete
[182] Fix | Delete
## -------------------- pickle support -------------------
[183] Fix | Delete
[184] Fix | Delete
# Issue 17489: Since __reduce__ was defined to fix #759889 this is no
[185] Fix | Delete
# longer called; we leave it here because it has been here since random was
[186] Fix | Delete
# rewritten back in 2001 and why risk breaking something.
[187] Fix | Delete
def __getstate__(self): # for pickle
[188] Fix | Delete
return self.getstate()
[189] Fix | Delete
[190] Fix | Delete
def __setstate__(self, state): # for pickle
[191] Fix | Delete
self.setstate(state)
[192] Fix | Delete
[193] Fix | Delete
def __reduce__(self):
[194] Fix | Delete
return self.__class__, (), self.getstate()
[195] Fix | Delete
[196] Fix | Delete
## -------------------- integer methods -------------------
[197] Fix | Delete
[198] Fix | Delete
def randrange(self, start, stop=None, step=1, _int=int):
[199] Fix | Delete
"""Choose a random item from range(start, stop[, step]).
[200] Fix | Delete
[201] Fix | Delete
This fixes the problem with randint() which includes the
[202] Fix | Delete
endpoint; in Python this is usually not what you want.
[203] Fix | Delete
[204] Fix | Delete
"""
[205] Fix | Delete
[206] Fix | Delete
# This code is a bit messy to make it fast for the
[207] Fix | Delete
# common case while still doing adequate error checking.
[208] Fix | Delete
istart = _int(start)
[209] Fix | Delete
if istart != start:
[210] Fix | Delete
raise ValueError("non-integer arg 1 for randrange()")
[211] Fix | Delete
if stop is None:
[212] Fix | Delete
if istart > 0:
[213] Fix | Delete
return self._randbelow(istart)
[214] Fix | Delete
raise ValueError("empty range for randrange()")
[215] Fix | Delete
[216] Fix | Delete
# stop argument supplied.
[217] Fix | Delete
istop = _int(stop)
[218] Fix | Delete
if istop != stop:
[219] Fix | Delete
raise ValueError("non-integer stop for randrange()")
[220] Fix | Delete
width = istop - istart
[221] Fix | Delete
if step == 1 and width > 0:
[222] Fix | Delete
return istart + self._randbelow(width)
[223] Fix | Delete
if step == 1:
[224] Fix | Delete
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
[225] Fix | Delete
[226] Fix | Delete
# Non-unit step argument supplied.
[227] Fix | Delete
istep = _int(step)
[228] Fix | Delete
if istep != step:
[229] Fix | Delete
raise ValueError("non-integer step for randrange()")
[230] Fix | Delete
if istep > 0:
[231] Fix | Delete
n = (width + istep - 1) // istep
[232] Fix | Delete
elif istep < 0:
[233] Fix | Delete
n = (width + istep + 1) // istep
[234] Fix | Delete
else:
[235] Fix | Delete
raise ValueError("zero step for randrange()")
[236] Fix | Delete
[237] Fix | Delete
if n <= 0:
[238] Fix | Delete
raise ValueError("empty range for randrange()")
[239] Fix | Delete
[240] Fix | Delete
return istart + istep*self._randbelow(n)
[241] Fix | Delete
[242] Fix | Delete
def randint(self, a, b):
[243] Fix | Delete
"""Return random integer in range [a, b], including both end points.
[244] Fix | Delete
"""
[245] Fix | Delete
[246] Fix | Delete
return self.randrange(a, b+1)
[247] Fix | Delete
[248] Fix | Delete
def _randbelow_with_getrandbits(self, n):
[249] Fix | Delete
"Return a random int in the range [0,n). Raises ValueError if n==0."
[250] Fix | Delete
[251] Fix | Delete
getrandbits = self.getrandbits
[252] Fix | Delete
k = n.bit_length() # don't use (n-1) here because n can be 1
[253] Fix | Delete
r = getrandbits(k) # 0 <= r < 2**k
[254] Fix | Delete
while r >= n:
[255] Fix | Delete
r = getrandbits(k)
[256] Fix | Delete
return r
[257] Fix | Delete
[258] Fix | Delete
def _randbelow_without_getrandbits(self, n, int=int, maxsize=1<<BPF):
[259] Fix | Delete
"""Return a random int in the range [0,n). Raises ValueError if n==0.
[260] Fix | Delete
[261] Fix | Delete
The implementation does not use getrandbits, but only random.
[262] Fix | Delete
"""
[263] Fix | Delete
[264] Fix | Delete
random = self.random
[265] Fix | Delete
if n >= maxsize:
[266] Fix | Delete
_warn("Underlying random() generator does not supply \n"
[267] Fix | Delete
"enough bits to choose from a population range this large.\n"
[268] Fix | Delete
"To remove the range limitation, add a getrandbits() method.")
[269] Fix | Delete
return int(random() * n)
[270] Fix | Delete
if n == 0:
[271] Fix | Delete
raise ValueError("Boundary cannot be zero")
[272] Fix | Delete
rem = maxsize % n
[273] Fix | Delete
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
[274] Fix | Delete
r = random()
[275] Fix | Delete
while r >= limit:
[276] Fix | Delete
r = random()
[277] Fix | Delete
return int(r*maxsize) % n
[278] Fix | Delete
[279] Fix | Delete
_randbelow = _randbelow_with_getrandbits
[280] Fix | Delete
[281] Fix | Delete
## -------------------- sequence methods -------------------
[282] Fix | Delete
[283] Fix | Delete
def choice(self, seq):
[284] Fix | Delete
"""Choose a random element from a non-empty sequence."""
[285] Fix | Delete
try:
[286] Fix | Delete
i = self._randbelow(len(seq))
[287] Fix | Delete
except ValueError:
[288] Fix | Delete
raise IndexError('Cannot choose from an empty sequence') from None
[289] Fix | Delete
return seq[i]
[290] Fix | Delete
[291] Fix | Delete
def shuffle(self, x, random=None):
[292] Fix | Delete
"""Shuffle list x in place, and return None.
[293] Fix | Delete
[294] Fix | Delete
Optional argument random is a 0-argument function returning a
[295] Fix | Delete
random float in [0.0, 1.0); if it is the default None, the
[296] Fix | Delete
standard random.random will be used.
[297] Fix | Delete
[298] Fix | Delete
"""
[299] Fix | Delete
[300] Fix | Delete
if random is None:
[301] Fix | Delete
randbelow = self._randbelow
[302] Fix | Delete
for i in reversed(range(1, len(x))):
[303] Fix | Delete
# pick an element in x[:i+1] with which to exchange x[i]
[304] Fix | Delete
j = randbelow(i+1)
[305] Fix | Delete
x[i], x[j] = x[j], x[i]
[306] Fix | Delete
else:
[307] Fix | Delete
_int = int
[308] Fix | Delete
for i in reversed(range(1, len(x))):
[309] Fix | Delete
# pick an element in x[:i+1] with which to exchange x[i]
[310] Fix | Delete
j = _int(random() * (i+1))
[311] Fix | Delete
x[i], x[j] = x[j], x[i]
[312] Fix | Delete
[313] Fix | Delete
def sample(self, population, k):
[314] Fix | Delete
"""Chooses k unique random elements from a population sequence or set.
[315] Fix | Delete
[316] Fix | Delete
Returns a new list containing elements from the population while
[317] Fix | Delete
leaving the original population unchanged. The resulting list is
[318] Fix | Delete
in selection order so that all sub-slices will also be valid random
[319] Fix | Delete
samples. This allows raffle winners (the sample) to be partitioned
[320] Fix | Delete
into grand prize and second place winners (the subslices).
[321] Fix | Delete
[322] Fix | Delete
Members of the population need not be hashable or unique. If the
[323] Fix | Delete
population contains repeats, then each occurrence is a possible
[324] Fix | Delete
selection in the sample.
[325] Fix | Delete
[326] Fix | Delete
To choose a sample in a range of integers, use range as an argument.
[327] Fix | Delete
This is especially fast and space efficient for sampling from a
[328] Fix | Delete
large population: sample(range(10000000), 60)
[329] Fix | Delete
"""
[330] Fix | Delete
[331] Fix | Delete
# Sampling without replacement entails tracking either potential
[332] Fix | Delete
# selections (the pool) in a list or previous selections in a set.
[333] Fix | Delete
[334] Fix | Delete
# When the number of selections is small compared to the
[335] Fix | Delete
# population, then tracking selections is efficient, requiring
[336] Fix | Delete
# only a small set and an occasional reselection. For
[337] Fix | Delete
# a larger number of selections, the pool tracking method is
[338] Fix | Delete
# preferred since the list takes less space than the
[339] Fix | Delete
# set and it doesn't suffer from frequent reselections.
[340] Fix | Delete
[341] Fix | Delete
# The number of calls to _randbelow() is kept at or near k, the
[342] Fix | Delete
# theoretical minimum. This is important because running time
[343] Fix | Delete
# is dominated by _randbelow() and because it extracts the
[344] Fix | Delete
# least entropy from the underlying random number generators.
[345] Fix | Delete
[346] Fix | Delete
# Memory requirements are kept to the smaller of a k-length
[347] Fix | Delete
# set or an n-length list.
[348] Fix | Delete
[349] Fix | Delete
# There are other sampling algorithms that do not require
[350] Fix | Delete
# auxiliary memory, but they were rejected because they made
[351] Fix | Delete
# too many calls to _randbelow(), making them slower and
[352] Fix | Delete
# causing them to eat more entropy than necessary.
[353] Fix | Delete
[354] Fix | Delete
if isinstance(population, _Set):
[355] Fix | Delete
population = tuple(population)
[356] Fix | Delete
if not isinstance(population, _Sequence):
[357] Fix | Delete
raise TypeError("Population must be a sequence or set. For dicts, use list(d).")
[358] Fix | Delete
randbelow = self._randbelow
[359] Fix | Delete
n = len(population)
[360] Fix | Delete
if not 0 <= k <= n:
[361] Fix | Delete
raise ValueError("Sample larger than population or is negative")
[362] Fix | Delete
result = [None] * k
[363] Fix | Delete
setsize = 21 # size of a small set minus size of an empty list
[364] Fix | Delete
if k > 5:
[365] Fix | Delete
setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
[366] Fix | Delete
if n <= setsize:
[367] Fix | Delete
# An n-length list is smaller than a k-length set
[368] Fix | Delete
pool = list(population)
[369] Fix | Delete
for i in range(k): # invariant: non-selected at [0,n-i)
[370] Fix | Delete
j = randbelow(n-i)
[371] Fix | Delete
result[i] = pool[j]
[372] Fix | Delete
pool[j] = pool[n-i-1] # move non-selected item into vacancy
[373] Fix | Delete
else:
[374] Fix | Delete
selected = set()
[375] Fix | Delete
selected_add = selected.add
[376] Fix | Delete
for i in range(k):
[377] Fix | Delete
j = randbelow(n)
[378] Fix | Delete
while j in selected:
[379] Fix | Delete
j = randbelow(n)
[380] Fix | Delete
selected_add(j)
[381] Fix | Delete
result[i] = population[j]
[382] Fix | Delete
return result
[383] Fix | Delete
[384] Fix | Delete
def choices(self, population, weights=None, *, cum_weights=None, k=1):
[385] Fix | Delete
"""Return a k sized list of population elements chosen with replacement.
[386] Fix | Delete
[387] Fix | Delete
If the relative weights or cumulative weights are not specified,
[388] Fix | Delete
the selections are made with equal probability.
[389] Fix | Delete
[390] Fix | Delete
"""
[391] Fix | Delete
random = self.random
[392] Fix | Delete
n = len(population)
[393] Fix | Delete
if cum_weights is None:
[394] Fix | Delete
if weights is None:
[395] Fix | Delete
_int = int
[396] Fix | Delete
n += 0.0 # convert to float for a small speed improvement
[397] Fix | Delete
return [population[_int(random() * n)] for i in _repeat(None, k)]
[398] Fix | Delete
cum_weights = list(_accumulate(weights))
[399] Fix | Delete
elif weights is not None:
[400] Fix | Delete
raise TypeError('Cannot specify both weights and cumulative weights')
[401] Fix | Delete
if len(cum_weights) != n:
[402] Fix | Delete
raise ValueError('The number of weights does not match the population')
[403] Fix | Delete
bisect = _bisect
[404] Fix | Delete
total = cum_weights[-1] + 0.0 # convert to float
[405] Fix | Delete
hi = n - 1
[406] Fix | Delete
return [population[bisect(cum_weights, random() * total, 0, hi)]
[407] Fix | Delete
for i in _repeat(None, k)]
[408] Fix | Delete
[409] Fix | Delete
## -------------------- real-valued distributions -------------------
[410] Fix | Delete
[411] Fix | Delete
## -------------------- uniform distribution -------------------
[412] Fix | Delete
[413] Fix | Delete
def uniform(self, a, b):
[414] Fix | Delete
"Get a random number in the range [a, b) or [a, b] depending on rounding."
[415] Fix | Delete
return a + (b-a) * self.random()
[416] Fix | Delete
[417] Fix | Delete
## -------------------- triangular --------------------
[418] Fix | Delete
[419] Fix | Delete
def triangular(self, low=0.0, high=1.0, mode=None):
[420] Fix | Delete
"""Triangular distribution.
[421] Fix | Delete
[422] Fix | Delete
Continuous distribution bounded by given lower and upper limits,
[423] Fix | Delete
and having a given mode value in-between.
[424] Fix | Delete
[425] Fix | Delete
http://en.wikipedia.org/wiki/Triangular_distribution
[426] Fix | Delete
[427] Fix | Delete
"""
[428] Fix | Delete
u = self.random()
[429] Fix | Delete
try:
[430] Fix | Delete
c = 0.5 if mode is None else (mode - low) / (high - low)
[431] Fix | Delete
except ZeroDivisionError:
[432] Fix | Delete
return low
[433] Fix | Delete
if u > c:
[434] Fix | Delete
u = 1.0 - u
[435] Fix | Delete
c = 1.0 - c
[436] Fix | Delete
low, high = high, low
[437] Fix | Delete
return low + (high - low) * _sqrt(u * c)
[438] Fix | Delete
[439] Fix | Delete
## -------------------- normal distribution --------------------
[440] Fix | Delete
[441] Fix | Delete
def normalvariate(self, mu, sigma):
[442] Fix | Delete
"""Normal distribution.
[443] Fix | Delete
[444] Fix | Delete
mu is the mean, and sigma is the standard deviation.
[445] Fix | Delete
[446] Fix | Delete
"""
[447] Fix | Delete
# mu = mean, sigma = standard deviation
[448] Fix | Delete
[449] Fix | Delete
# Uses Kinderman and Monahan method. Reference: Kinderman,
[450] Fix | Delete
# A.J. and Monahan, J.F., "Computer generation of random
[451] Fix | Delete
# variables using the ratio of uniform deviates", ACM Trans
[452] Fix | Delete
# Math Software, 3, (1977), pp257-260.
[453] Fix | Delete
[454] Fix | Delete
random = self.random
[455] Fix | Delete
while 1:
[456] Fix | Delete
u1 = random()
[457] Fix | Delete
u2 = 1.0 - random()
[458] Fix | Delete
z = NV_MAGICCONST*(u1-0.5)/u2
[459] Fix | Delete
zz = z*z/4.0
[460] Fix | Delete
if zz <= -_log(u2):
[461] Fix | Delete
break
[462] Fix | Delete
return mu + z*sigma
[463] Fix | Delete
[464] Fix | Delete
## -------------------- lognormal distribution --------------------
[465] Fix | Delete
[466] Fix | Delete
def lognormvariate(self, mu, sigma):
[467] Fix | Delete
"""Log normal distribution.
[468] Fix | Delete
[469] Fix | Delete
If you take the natural logarithm of this distribution, you'll get a
[470] Fix | Delete
normal distribution with mean mu and standard deviation sigma.
[471] Fix | Delete
mu can have any value, and sigma must be greater than zero.
[472] Fix | Delete
[473] Fix | Delete
"""
[474] Fix | Delete
return _exp(self.normalvariate(mu, sigma))
[475] Fix | Delete
[476] Fix | Delete
## -------------------- exponential distribution --------------------
[477] Fix | Delete
[478] Fix | Delete
def expovariate(self, lambd):
[479] Fix | Delete
"""Exponential distribution.
[480] Fix | Delete
[481] Fix | Delete
lambd is 1.0 divided by the desired mean. It should be
[482] Fix | Delete
nonzero. (The parameter would be called "lambda", but that is
[483] Fix | Delete
a reserved word in Python.) Returned values range from 0 to
[484] Fix | Delete
positive infinity if lambd is positive, and from negative
[485] Fix | Delete
infinity to 0 if lambd is negative.
[486] Fix | Delete
[487] Fix | Delete
"""
[488] Fix | Delete
# lambd: rate lambd = 1/mean
[489] Fix | Delete
# ('lambda' is a Python reserved word)
[490] Fix | Delete
[491] Fix | Delete
# we use 1-random() instead of random() to preclude the
[492] Fix | Delete
# possibility of taking the log of zero.
[493] Fix | Delete
return -_log(1.0 - self.random())/lambd
[494] Fix | Delete
[495] Fix | Delete
## -------------------- von Mises distribution --------------------
[496] Fix | Delete
[497] Fix | Delete
def vonmisesvariate(self, mu, kappa):
[498] Fix | Delete
"""Circular data distribution.
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function