Back to index

python3.2  3.2.2
Classes | Functions | Variables
random Namespace Reference

Classes

class  Random
class  SystemRandom
 --------------- Operating System Random Source ------------------ More...

Functions

def __getstate__
 ---- Methods below this point do not need to be overridden when ---- subclassing for the purpose of using a different core generator.
def __setstate__
def __reduce__
def randrange
 -------------------- integer methods -------------------
def randint
def _randbelow
def choice
 -------------------- sequence methods -------------------
def shuffle
def sample
def uniform
 -------------------- real-valued distributions -------------------
def triangular
 -------------------- triangular --------------------
def normalvariate
 -------------------- normal distribution --------------------
def lognormvariate
 -------------------- lognormal distribution --------------------
def expovariate
 -------------------- exponential distribution --------------------
def vonmisesvariate
 -------------------- von Mises distribution --------------------
def gammavariate
 -------------------- gamma distribution --------------------
def gauss
 -------------------- Gauss (faster alternative) --------------------
def betavariate
 -------------------- beta -------------------- See http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html for Ivan Frohne's insightful analysis of why the original implementation:
def paretovariate
 -------------------- Pareto --------------------
def weibullvariate
 -------------------- Weibull --------------------
def _test_generator
 -------------------- test program --------------------
def _test

Variables

list __all__
int NV_MAGICCONST = 4
float TWOPI = 2.0
tuple LOG4 = _log(4.0)
float SG_MAGICCONST = 1.0
int BPF = 53
int RECIP_BPF = 2
tuple _inst = Random()
 seed = _inst.seed
 random = _inst.random
 uniform = _inst.uniform
 triangular = _inst.triangular
 randint = _inst.randint
 choice = _inst.choice
 randrange = _inst.randrange
 sample = _inst.sample
 shuffle = _inst.shuffle
 normalvariate = _inst.normalvariate
 lognormvariate = _inst.lognormvariate
 expovariate = _inst.expovariate
 vonmisesvariate = _inst.vonmisesvariate
 gammavariate = _inst.gammavariate
 gauss = _inst.gauss
 betavariate = _inst.betavariate
 paretovariate = _inst.paretovariate
 weibullvariate = _inst.weibullvariate
 getstate = _inst.getstate
 setstate = _inst.setstate
 getrandbits = _inst.getrandbits
 gauss_next

Detailed Description

Random variable generators.

integers
--------
       uniform within range

sequences
---------
       pick random element
       pick random sample
       generate random permutation

distributions on the real line:
------------------------------
       uniform
       triangular
       normal (Gaussian)
       lognormal
       negative exponential
       gamma
       beta
       pareto
       Weibull

distributions on the circle (angles 0 to 2pi)
---------------------------------------------
       circular uniform
       von Mises

General notes on the underlying Mersenne Twister core generator:

* The period is 2**19937-1.
* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
  and is, therefore, threadsafe.

Function Documentation

def random.__getstate__ (   self)

---- Methods below this point do not need to be overridden when ---- subclassing for the purpose of using a different core generator.

-------------------- pickle support -------------------

Definition at line 155 of file random.py.

00155 
00156     def __getstate__(self): # for pickle
00157         return self.getstate()

Here is the caller graph for this function:

def random.__reduce__ (   self)

Definition at line 161 of file random.py.

00161 
00162     def __reduce__(self):
00163         return self.__class__, (), self.getstate()

Here is the caller graph for this function:

def random.__setstate__ (   self,
  state 
)

Definition at line 158 of file random.py.

00158 
00159     def __setstate__(self, state):  # for pickle
00160         self.setstate(state)

Here is the caller graph for this function:

def random._randbelow (   self,
  n,
  int = int,
  maxsize = 1<<BPF,
  type = type,
  Method = _MethodType,
  BuiltinMethod = _BuiltinMethodType 
) [private]

Definition at line 218 of file random.py.

00218 
00219                    Method=_MethodType, BuiltinMethod=_BuiltinMethodType):
00220         "Return a random int in the range [0,n).  Raises ValueError if n==0."
00221 
00222         getrandbits = self.getrandbits
00223         # Only call self.getrandbits if the original random() builtin method
00224         # has not been overridden or if a new getrandbits() was supplied.
00225         if type(self.random) is BuiltinMethod or type(getrandbits) is Method:
00226             k = n.bit_length()  # don't use (n-1) here because n can be 1
00227             r = getrandbits(k)          # 0 <= r < 2**k
00228             while r >= n:
00229                 r = getrandbits(k)
00230             return r
00231         # There's an overriden random() method but no new getrandbits() method,
00232         # so we can only use random() from here.
00233         random = self.random
00234         if n >= maxsize:
00235             _warn("Underlying random() generator does not supply \n"
00236                 "enough bits to choose from a population range this large.\n"
00237                 "To remove the range limitation, add a getrandbits() method.")
00238             return int(random() * n)
00239         rem = maxsize % n
00240         limit = (maxsize - rem) / maxsize   # int(limit * maxsize) % n == 0
00241         r = random()
00242         while r >= limit:
00243             r = random()
00244         return int(r*maxsize) % n

Here is the caller graph for this function:

def random._test (   N = 2000) [private]

Definition at line 681 of file random.py.

00681 
00682 def _test(N=2000):
00683     _test_generator(N, random, ())
00684     _test_generator(N, normalvariate, (0.0, 1.0))
00685     _test_generator(N, lognormvariate, (0.0, 1.0))
00686     _test_generator(N, vonmisesvariate, (0.0, 1.0))
00687     _test_generator(N, gammavariate, (0.01, 1.0))
00688     _test_generator(N, gammavariate, (0.1, 1.0))
00689     _test_generator(N, gammavariate, (0.1, 2.0))
00690     _test_generator(N, gammavariate, (0.5, 1.0))
00691     _test_generator(N, gammavariate, (0.9, 1.0))
00692     _test_generator(N, gammavariate, (1.0, 1.0))
00693     _test_generator(N, gammavariate, (2.0, 1.0))
00694     _test_generator(N, gammavariate, (20.0, 1.0))
00695     _test_generator(N, gammavariate, (200.0, 1.0))
00696     _test_generator(N, gauss, (0.0, 1.0))
00697     _test_generator(N, betavariate, (3.0, 3.0))
00698     _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0))
00699 
00700 # Create one instance, seeded from current time, and export its methods
00701 # as module-level functions.  The functions share state across all uses
00702 #(both in the user's code and in the Python libraries), but that's fine
00703 # for most programs and is easier for the casual user than making them
00704 # instantiate their own Random() instance.

Here is the call graph for this function:

def random._test_generator (   n,
  func,
  args 
) [private]

-------------------- test program --------------------

Definition at line 659 of file random.py.

00659 
00660 def _test_generator(n, func, args):
00661     import time
00662     print(n, 'times', func.__name__)
00663     total = 0.0
00664     sqsum = 0.0
00665     smallest = 1e10
00666     largest = -1e10
00667     t0 = time.time()
00668     for i in range(n):
00669         x = func(*args)
00670         total += x
00671         sqsum = sqsum + x*x
00672         smallest = min(x, smallest)
00673         largest = max(x, largest)
00674     t1 = time.time()
00675     print(round(t1-t0, 3), 'sec,', end=' ')
00676     avg = total/n
00677     stddev = _sqrt(sqsum/n - avg*avg)
00678     print('avg %g, stddev %g, min %g, max %g' % \
00679               (avg, stddev, smallest, largest))
00680 

Here is the call graph for this function:

Here is the caller graph for this function:

def random.betavariate (   self,
  alpha,
  beta 
)

-------------------- beta -------------------- See http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html for Ivan Frohne's insightful analysis of why the original implementation:

def betavariate(self, alpha, beta):

Discrete Event Simulation in C, pp 87-88.

    y = self.expovariate(alpha)
    z = self.expovariate(1.0/beta)
    return z/(y+z)

was dead wrong, and how it probably got that way.

Beta distribution.

Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.

Definition at line 586 of file random.py.

00586 
00587     def betavariate(self, alpha, beta):
00588         """Beta distribution.
00589 
00590         Conditions on the parameters are alpha > 0 and beta > 0.
00591         Returned values range between 0 and 1.
00592 
00593         """
00594 
00595         # This version due to Janne Sinkkonen, and matches all the std
00596         # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
00597         y = self.gammavariate(alpha, 1.)
00598         if y == 0:
00599             return 0.0
00600         else:
00601             return y / (y + self.gammavariate(beta, 1.))

def random.choice (   self,
  seq 
)

-------------------- sequence methods -------------------

Choose a random element from a non-empty sequence.

Definition at line 247 of file random.py.

00247 
00248     def choice(self, seq):
00249         """Choose a random element from a non-empty sequence."""
00250         try:
00251             i = self._randbelow(len(seq))
00252         except ValueError:
00253             raise IndexError('Cannot choose from an empty sequence')
00254         return seq[i]

Here is the caller graph for this function:

def random.expovariate (   self,
  lambd 
)

-------------------- exponential distribution --------------------

Exponential distribution.

lambd is 1.0 divided by the desired mean.  It should be
nonzero.  (The parameter would be called "lambda", but that is
a reserved word in Python.)  Returned values range from 0 to
positive infinity if lambd is positive, and from negative
infinity to 0 if lambd is negative.

Definition at line 392 of file random.py.

00392 
00393     def expovariate(self, lambd):
00394         """Exponential distribution.
00395 
00396         lambd is 1.0 divided by the desired mean.  It should be
00397         nonzero.  (The parameter would be called "lambda", but that is
00398         a reserved word in Python.)  Returned values range from 0 to
00399         positive infinity if lambd is positive, and from negative
00400         infinity to 0 if lambd is negative.
00401 
00402         """
00403         # lambd: rate lambd = 1/mean
00404         # ('lambda' is a Python reserved word)
00405 
00406         # we use 1-random() instead of random() to preclude the
00407         # possibility of taking the log of zero.
00408         return -_log(1.0 - self.random())/lambd

Here is the call graph for this function:

Here is the caller graph for this function:

def random.gammavariate (   self,
  alpha,
  beta 
)

-------------------- gamma distribution --------------------

Gamma distribution.  Not the gamma function!

Conditions on the parameters are alpha > 0 and beta > 0.

The probability distribution function is:

            x ** (alpha - 1) * math.exp(-x / beta)
  pdf(x) =  --------------------------------------
              math.gamma(alpha) * beta ** alpha

Definition at line 461 of file random.py.

00461 
00462     def gammavariate(self, alpha, beta):
00463         """Gamma distribution.  Not the gamma function!
00464 
00465         Conditions on the parameters are alpha > 0 and beta > 0.
00466 
00467         The probability distribution function is:
00468 
00469                     x ** (alpha - 1) * math.exp(-x / beta)
00470           pdf(x) =  --------------------------------------
00471                       math.gamma(alpha) * beta ** alpha
00472 
00473         """
00474 
00475         # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
00476 
00477         # Warning: a few older sources define the gamma distribution in terms
00478         # of alpha > -1.0
00479         if alpha <= 0.0 or beta <= 0.0:
00480             raise ValueError('gammavariate: alpha and beta must be > 0.0')
00481 
00482         random = self.random
00483         if alpha > 1.0:
00484 
00485             # Uses R.C.H. Cheng, "The generation of Gamma
00486             # variables with non-integral shape parameters",
00487             # Applied Statistics, (1977), 26, No. 1, p71-74
00488 
00489             ainv = _sqrt(2.0 * alpha - 1.0)
00490             bbb = alpha - LOG4
00491             ccc = alpha + ainv
00492 
00493             while 1:
00494                 u1 = random()
00495                 if not 1e-7 < u1 < .9999999:
00496                     continue
00497                 u2 = 1.0 - random()
00498                 v = _log(u1/(1.0-u1))/ainv
00499                 x = alpha*_exp(v)
00500                 z = u1*u1*u2
00501                 r = bbb+ccc*v-x
00502                 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
00503                     return x * beta
00504 
00505         elif alpha == 1.0:
00506             # expovariate(1)
00507             u = random()
00508             while u <= 1e-7:
00509                 u = random()
00510             return -_log(u) * beta
00511 
00512         else:   # alpha is between 0 and 1 (exclusive)
00513 
00514             # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
00515 
00516             while 1:
00517                 u = random()
00518                 b = (_e + alpha)/_e
00519                 p = b*u
00520                 if p <= 1.0:
00521                     x = p ** (1.0/alpha)
00522                 else:
00523                     x = -_log((b-p)/alpha)
00524                 u1 = random()
00525                 if p > 1.0:
00526                     if u1 <= x ** (alpha - 1.0):
00527                         break
00528                 elif u1 <= _exp(-x):
00529                     break
00530             return x * beta

Here is the call graph for this function:

def random.gauss (   self,
  mu,
  sigma 
)

-------------------- Gauss (faster alternative) --------------------

Gaussian distribution.

mu is the mean, and sigma is the standard deviation.  This is
slightly faster than the normalvariate() function.

Not thread-safe without a lock around calls.

Definition at line 533 of file random.py.

00533 
00534     def gauss(self, mu, sigma):
00535         """Gaussian distribution.
00536 
00537         mu is the mean, and sigma is the standard deviation.  This is
00538         slightly faster than the normalvariate() function.
00539 
00540         Not thread-safe without a lock around calls.
00541 
00542         """
00543 
00544         # When x and y are two variables from [0, 1), uniformly
00545         # distributed, then
00546         #
00547         #    cos(2*pi*x)*sqrt(-2*log(1-y))
00548         #    sin(2*pi*x)*sqrt(-2*log(1-y))
00549         #
00550         # are two *independent* variables with normal distribution
00551         # (mu = 0, sigma = 1).
00552         # (Lambert Meertens)
00553         # (corrected version; bug discovered by Mike Miller, fixed by LM)
00554 
00555         # Multithreading note: When two threads call this function
00556         # simultaneously, it is possible that they will receive the
00557         # same return value.  The window is very small though.  To
00558         # avoid this, you have to use a lock around all calls.  (I
00559         # didn't want to slow this down in the serial case by using a
00560         # lock here.)
00561 
00562         random = self.random
00563         z = self.gauss_next
00564         self.gauss_next = None
00565         if z is None:
00566             x2pi = random() * TWOPI
00567             g2rad = _sqrt(-2.0 * _log(1.0 - random()))
00568             z = _cos(x2pi) * g2rad
00569             self.gauss_next = _sin(x2pi) * g2rad
00570 
00571         return mu + z*sigma

def random.lognormvariate (   self,
  mu,
  sigma 
)

-------------------- lognormal distribution --------------------

Log normal distribution.

If you take the natural logarithm of this distribution, you'll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.

Definition at line 380 of file random.py.

00380 
00381     def lognormvariate(self, mu, sigma):
00382         """Log normal distribution.
00383 
00384         If you take the natural logarithm of this distribution, you'll get a
00385         normal distribution with mean mu and standard deviation sigma.
00386         mu can have any value, and sigma must be greater than zero.
00387 
00388         """
00389         return _exp(self.normalvariate(mu, sigma))

Here is the caller graph for this function:

def random.normalvariate (   self,
  mu,
  sigma 
)

-------------------- normal distribution --------------------

Normal distribution.

mu is the mean, and sigma is the standard deviation.

Definition at line 355 of file random.py.

00355 
00356     def normalvariate(self, mu, sigma):
00357         """Normal distribution.
00358 
00359         mu is the mean, and sigma is the standard deviation.
00360 
00361         """
00362         # mu = mean, sigma = standard deviation
00363 
00364         # Uses Kinderman and Monahan method. Reference: Kinderman,
00365         # A.J. and Monahan, J.F., "Computer generation of random
00366         # variables using the ratio of uniform deviates", ACM Trans
00367         # Math Software, 3, (1977), pp257-260.
00368 
00369         random = self.random
00370         while 1:
00371             u1 = random()
00372             u2 = 1.0 - random()
00373             z = NV_MAGICCONST*(u1-0.5)/u2
00374             zz = z*z/4.0
00375             if zz <= -_log(u2):
00376                 break
00377         return mu + z*sigma

Here is the call graph for this function:

def random.paretovariate (   self,
  alpha 
)

-------------------- Pareto --------------------

Pareto distribution.  alpha is the shape parameter.

Definition at line 604 of file random.py.

00604 
00605     def paretovariate(self, alpha):
00606         """Pareto distribution.  alpha is the shape parameter."""
00607         # Jain, pg. 495
00608 
00609         u = 1.0 - self.random()
00610         return 1.0 / u ** (1.0/alpha)

def random.randint (   self,
  a,
  b 
)
Return random integer in range [a, b], including both end points.

Definition at line 211 of file random.py.

00211 
00212     def randint(self, a, b):
00213         """Return random integer in range [a, b], including both end points.
00214         """
00215 
00216         return self.randrange(a, b+1)

Here is the call graph for this function:

Here is the caller graph for this function:

def random.randrange (   self,
  start,
  stop = None,
  step = 1,
  int = int 
)

-------------------- integer methods -------------------

Choose a random item from range(start, stop[, step]).

This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.

Do not supply the 'int' argument.

Definition at line 166 of file random.py.

00166 
00167     def randrange(self, start, stop=None, step=1, int=int):
00168         """Choose a random item from range(start, stop[, step]).
00169 
00170         This fixes the problem with randint() which includes the
00171         endpoint; in Python this is usually not what you want.
00172 
00173         Do not supply the 'int' argument.
00174         """
00175 
00176         # This code is a bit messy to make it fast for the
00177         # common case while still doing adequate error checking.
00178         istart = int(start)
00179         if istart != start:
00180             raise ValueError("non-integer arg 1 for randrange()")
00181         if stop is None:
00182             if istart > 0:
00183                 return self._randbelow(istart)
00184             raise ValueError("empty range for randrange()")
00185 
00186         # stop argument supplied.
00187         istop = int(stop)
00188         if istop != stop:
00189             raise ValueError("non-integer stop for randrange()")
00190         width = istop - istart
00191         if step == 1 and width > 0:
00192             return istart + self._randbelow(width)
00193         if step == 1:
00194             raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
00195 
00196         # Non-unit step argument supplied.
00197         istep = int(step)
00198         if istep != step:
00199             raise ValueError("non-integer step for randrange()")
00200         if istep > 0:
00201             n = (width + istep - 1) // istep
00202         elif istep < 0:
00203             n = (width + istep + 1) // istep
00204         else:
00205             raise ValueError("zero step for randrange()")
00206 
00207         if n <= 0:
00208             raise ValueError("empty range for randrange()")
00209 
00210         return istart + istep*self._randbelow(n)

def random.sample (   self,
  population,
  k 
)
Chooses k unique random elements from a population sequence or set.

Returns a new list containing elements from the population while
leaving the original population unchanged.  The resulting list is
in selection order so that all sub-slices will also be valid random
samples.  This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique.  If the
population contains repeats, then each occurrence is a possible
selection in the sample.

To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population:   sample(range(10000000), 60)

Definition at line 268 of file random.py.

00268 
00269     def sample(self, population, k):
00270         """Chooses k unique random elements from a population sequence or set.
00271 
00272         Returns a new list containing elements from the population while
00273         leaving the original population unchanged.  The resulting list is
00274         in selection order so that all sub-slices will also be valid random
00275         samples.  This allows raffle winners (the sample) to be partitioned
00276         into grand prize and second place winners (the subslices).
00277 
00278         Members of the population need not be hashable or unique.  If the
00279         population contains repeats, then each occurrence is a possible
00280         selection in the sample.
00281 
00282         To choose a sample in a range of integers, use range as an argument.
00283         This is especially fast and space efficient for sampling from a
00284         large population:   sample(range(10000000), 60)
00285         """
00286 
00287         # Sampling without replacement entails tracking either potential
00288         # selections (the pool) in a list or previous selections in a set.
00289 
00290         # When the number of selections is small compared to the
00291         # population, then tracking selections is efficient, requiring
00292         # only a small set and an occasional reselection.  For
00293         # a larger number of selections, the pool tracking method is
00294         # preferred since the list takes less space than the
00295         # set and it doesn't suffer from frequent reselections.
00296 
00297         if isinstance(population, _Set):
00298             population = tuple(population)
00299         if not isinstance(population, _Sequence):
00300             raise TypeError("Population must be a sequence or set.  For dicts, use list(d).")
00301         randbelow = self._randbelow
00302         n = len(population)
00303         if not 0 <= k <= n:
00304             raise ValueError("Sample larger than population")
00305         result = [None] * k
00306         setsize = 21        # size of a small set minus size of an empty list
00307         if k > 5:
00308             setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
00309         if n <= setsize:
00310             # An n-length list is smaller than a k-length set
00311             pool = list(population)
00312             for i in range(k):         # invariant:  non-selected at [0,n-i)
00313                 j = randbelow(n-i)
00314                 result[i] = pool[j]
00315                 pool[j] = pool[n-i-1]   # move non-selected item into vacancy
00316         else:
00317             selected = set()
00318             selected_add = selected.add
00319             for i in range(k):
00320                 j = randbelow(n)
00321                 while j in selected:
00322                     j = randbelow(n)
00323                 selected_add(j)
00324                 result[i] = population[j]
00325         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def random.shuffle (   self,
  x,
  random = None,
  int = int 
)
x, random=random.random -> shuffle list x in place; return None.

Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.

Definition at line 255 of file random.py.

00255 
00256     def shuffle(self, x, random=None, int=int):
00257         """x, random=random.random -> shuffle list x in place; return None.
00258 
00259         Optional arg random is a 0-argument function returning a random
00260         float in [0.0, 1.0); by default, the standard random.random.
00261         """
00262 
00263         randbelow = self._randbelow
00264         for i in reversed(range(1, len(x))):
00265             # pick an element in x[:i+1] with which to exchange x[i]
00266             j = randbelow(i+1) if random is None else int(random() * (i+1))
00267             x[i], x[j] = x[j], x[i]

Here is the caller graph for this function:

def random.triangular (   self,
  low = 0.0,
  high = 1.0,
  mode = None 
)

-------------------- triangular --------------------

Triangular distribution.

Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.

http://en.wikipedia.org/wiki/Triangular_distribution

Definition at line 336 of file random.py.

00336 
00337     def triangular(self, low=0.0, high=1.0, mode=None):
00338         """Triangular distribution.
00339 
00340         Continuous distribution bounded by given lower and upper limits,
00341         and having a given mode value in-between.
00342 
00343         http://en.wikipedia.org/wiki/Triangular_distribution
00344 
00345         """
00346         u = self.random()
00347         c = 0.5 if mode is None else (mode - low) / (high - low)
00348         if u > c:
00349             u = 1.0 - u
00350             c = 1.0 - c
00351             low, high = high, low
00352         return low + (high - low) * (u * c) ** 0.5

def random.uniform (   self,
  a,
  b 
)

-------------------- real-valued distributions -------------------

-------------------- uniform distribution -------------------

Definition at line 330 of file random.py.

00330 
00331     def uniform(self, a, b):
00332         "Get a random number in the range [a, b) or [a, b] depending on rounding."
00333         return a + (b-a) * self.random()

def random.vonmisesvariate (   self,
  mu,
  kappa 
)

-------------------- von Mises distribution --------------------

Circular data distribution.

mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero.  If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.

Definition at line 411 of file random.py.

00411 
00412     def vonmisesvariate(self, mu, kappa):
00413         """Circular data distribution.
00414 
00415         mu is the mean angle, expressed in radians between 0 and 2*pi, and
00416         kappa is the concentration parameter, which must be greater than or
00417         equal to zero.  If kappa is equal to zero, this distribution reduces
00418         to a uniform random angle over the range 0 to 2*pi.
00419 
00420         """
00421         # mu:    mean angle (in radians between 0 and 2*pi)
00422         # kappa: concentration parameter kappa (>= 0)
00423         # if kappa = 0 generate uniform random angle
00424 
00425         # Based upon an algorithm published in: Fisher, N.I.,
00426         # "Statistical Analysis of Circular Data", Cambridge
00427         # University Press, 1993.
00428 
00429         # Thanks to Magnus Kessler for a correction to the
00430         # implementation of step 4.
00431 
00432         random = self.random
00433         if kappa <= 1e-6:
00434             return TWOPI * random()
00435 
00436         a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)
00437         b = (a - _sqrt(2.0 * a))/(2.0 * kappa)
00438         r = (1.0 + b * b)/(2.0 * b)
00439 
00440         while 1:
00441             u1 = random()
00442 
00443             z = _cos(_pi * u1)
00444             f = (1.0 + r * z)/(r + z)
00445             c = kappa * (r - f)
00446 
00447             u2 = random()
00448 
00449             if u2 < c * (2.0 - c) or u2 <= c * _exp(1.0 - c):
00450                 break
00451 
00452         u3 = random()
00453         if u3 > 0.5:
00454             theta = (mu % TWOPI) + _acos(f)
00455         else:
00456             theta = (mu % TWOPI) - _acos(f)
00457 
00458         return theta

def random.weibullvariate (   self,
  alpha,
  beta 
)

-------------------- Weibull --------------------

Weibull distribution.

alpha is the scale parameter and beta is the shape parameter.

Definition at line 613 of file random.py.

00613 
00614     def weibullvariate(self, alpha, beta):
00615         """Weibull distribution.
00616 
00617         alpha is the scale parameter and beta is the shape parameter.
00618 
00619         """
00620         # Jain, pg. 499; bug fix courtesy Bill Arms
00621 
00622         u = 1.0 - self.random()
00623         return alpha * (-_log(u)) ** (1.0/beta)

Here is the call graph for this function:


Variable Documentation

Initial value:
00001 ["Random","seed","random","uniform","randint","choice","sample",
00002            "randrange","shuffle","normalvariate","lognormvariate",
00003            "expovariate","vonmisesvariate","gammavariate","triangular",
00004            "gauss","betavariate","paretovariate","weibullvariate",
00005            "getstate","setstate", "getrandbits",
00006            "SystemRandom"]

Definition at line 48 of file random.py.

tuple random._inst = Random()

Definition at line 705 of file random.py.

random.betavariate = _inst.betavariate

Definition at line 721 of file random.py.

Definition at line 59 of file random.py.

random.choice = _inst.choice

Definition at line 711 of file random.py.

random.expovariate = _inst.expovariate

Definition at line 717 of file random.py.

random.gammavariate = _inst.gammavariate

Definition at line 719 of file random.py.

random.gauss = _inst.gauss

Definition at line 720 of file random.py.

Definition at line 563 of file random.py.

random.getrandbits = _inst.getrandbits

Definition at line 726 of file random.py.

random.getstate = _inst.getstate

Definition at line 724 of file random.py.

tuple random.LOG4 = _log(4.0)

Definition at line 57 of file random.py.

random.lognormvariate = _inst.lognormvariate

Definition at line 716 of file random.py.

random.normalvariate = _inst.normalvariate

Definition at line 715 of file random.py.

Definition at line 55 of file random.py.

random.paretovariate = _inst.paretovariate

Definition at line 722 of file random.py.

random.randint = _inst.randint

Definition at line 710 of file random.py.

random.random = _inst.random

Definition at line 707 of file random.py.

random.randrange = _inst.randrange

Definition at line 712 of file random.py.

Definition at line 60 of file random.py.

random.sample = _inst.sample

Definition at line 713 of file random.py.

random.seed = _inst.seed

Definition at line 706 of file random.py.

random.setstate = _inst.setstate

Definition at line 725 of file random.py.

float random.SG_MAGICCONST = 1.0

Definition at line 58 of file random.py.

random.shuffle = _inst.shuffle

Definition at line 714 of file random.py.

random.triangular = _inst.triangular

Definition at line 709 of file random.py.

float random.TWOPI = 2.0

Definition at line 56 of file random.py.

random.uniform = _inst.uniform

Definition at line 708 of file random.py.

random.vonmisesvariate = _inst.vonmisesvariate

Definition at line 718 of file random.py.

random.weibullvariate = _inst.weibullvariate

Definition at line 723 of file random.py.