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