9.6.Random-generate pseudo-random numbers
Source Code: lib/random.py
This module implements pseudo-random number generators for various distributions.
This module implements pseudo-random number generation and various distributions
For integers, there are uniform selection from a range. For sequences, there was uniform selection of a random element, a function to generate a random permutation of a list in-pl Ace, and a function for random sampling without replacement.
For integers, this is the only number within a range; for sequences, this is a randomly selected element; a function that generates a proper random ordering of a list, or produces a random sampling without substitution.
On the real line, there is functions to compute uniform, Normal (Gaussian), lognormal, negative exponential, gamma, and B ETA distributions. For generating distributions of angles, the von Mises distribution is available.
Almost all module functions depend on the basic functionrandom (), which generates a random float uniformly in th e semi-open range [0.0, 1.0]. Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and are completely unsuitable for cryptograph IC purposes.
In fact, there are some computational uniform distributions, Normal (Gaussian) distributions, logarithmic normal distributions, complex exponential distributions, gamma distributions, and beta distributions. Available when generating angular distributions and Feng Mises distributions.
Almost all module functions rely on the underlying random () function, which is within a semi-open range [0.0, 1.0] (including 0.0, excluding 1.0), producing a random, single floating-point number,
The functions supplied by this module is actually bound methods of a hidden instance of therandom. Randomclass. You can instantiate your own instances of theRandomto get generators that don ' t share state.
Classrandom (), , andgetrandbits ()Method-this al Lowsrandrange ()to produce selections over an arbitrarily large Range.
Therandommodule also provides theSystemrandomclass which uses the system functionos.urandom () to generate random numbers from sources provided by the operating system.
Warning
The pseudo-random generators of this module should is not being used for security purposes. Useos.urandom ()orsystemrandomif you require a cryptographically secure pseudo-random number Generato R.
Bookkeeping functions:
Random.seed(
a=none,
version=2 )
Initialize the random number generator.
If A is omitted ornone, and the current system time is used. If randomness sources is provided by the operating system, they is used instead of the system time (see theos.urandom ()function for details on availability).
If A is an int., it is used directly.
With version 2 (the default), abytes, or
Random.GetState()
Return an object capturing the current internal state of the generator. This object can is passed toSetState ()to restore the state.
Random.SetState(
State)
State should has been obtained from a previous call toGetState (), andsetstate ()Restor ES the internal state of the the generator to what it is at the timeGetState ()was called.
Random.getrandbits(
k )
Returns a Python integer with k random bits. This method was supplied with the Mersennetwister generator and some other generators could also provide it as an optional PA RT of the API. When available,getrandbits ()enablesRandrange ()to handle arbitrarily large ranges.
Functions for integers:
random.Randrange(
stop )Random.Randrange(
start ,
stop [,
step ])
Return A randomly selected element fromrange (Start, stop, step). This is equivalent tochoice (range (Start, stop, Step)), but doesn ' t actually build a range object.
The positional argument pattern matches that ofrandrange ()are more sophisticated about producing equally distributed values. Formerly it used a style likeint (Random () *n)which could produce slightly uneven distributions.
Random.Randint(
a,
b )
Return a random integer n such thata <= N <= b. Aliasfor Randrange (A, b+1).
Functions for sequences:
Random.Choice(
seq )
Return a random element from the non-empty sequence seq. If seq is empty, raisesindexerror.
Random.Shuffle(
x[,
random])
Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); By default, the functionrandom ().
Note that for even rather smalllen (x), the total number of permutations of x is larger than the per IoD of the most random number generators; This implies is permutations of a long sequence can never be generated.
Random.Sample(
population,
k )
Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so, all sub-slices would also be valid random samples. This allows raffle winners (the sample) is partitioned into grand prize and second place winners (the Subslices).
Members of the population need is not being hashable or unique. If The population contains repeats, then each occurrence are a possible selection in the sample.
To choose a is a sample from a range of integers, with arange ()object as an argument. This was especially fast and space efficient for sampling from a large population:sample (Range (10000000)).
If the sample size is larger than the population size, avalueerroris raised.
The following functions generate specific real-valued distributions. Function parameters is named after the corresponding variables in the distribution's equation, as used in common Mathemat ical practice; Most of these equations can is found in any statistics text.
Random.Random()
Return the next random floating point number in the range [0.0, 1.0].
random.Uniform(
a ,
b )
Return A random floating point number n such thisa <= N <= bfora <= bandb <= N <= aforb < a.
The end-point valuebmay or is not being included in the range depending on floating-point rounding In the equationa + (b-a) * random ().
Random.Triangular(
Low,
High,
mode )
Return a random floating point number n such this low<= N <=High and with the specified m Ode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.
Random.betavariate(
Alpha,
beta )
Beta distribution. Conditions on the parameters isAlpha > 0andbeta > 0. Returned values range between 0 and 1.
random.expovariate(
lambd )
Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (the parameter would was called "lambda", but that's a reserved word in Python.) Returned values range from 0 to positive infinity if lambd are positive, and from negative infinity to 0 if LA MBD is negative.
Random.gammavariate(
Alpha,
beta )
Gamma distribution. ( not the gamma function!) Conditions on the parameters isAlpha > 0andbeta > 0.
The probability distribution function is:
X * * (alpha-1) * MATH.EXP (-x/beta) PDF (x) = --------------------------------------
Random.Gauss(
mu,
Sigma )
Gaussian distribution. Mu is the mean, and Sigma are the standard deviation. This is slightly faster than thenormalvariate ()function defined below.
Random.lognormvariate(
mu,
Sigma )
Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and Standar D deviation Sigma. Mu can has any value, and Sigma must is greater than zero.
Random.normalvariate(
mu,
Sigma )
Normal distribution. Mu is the mean, and Sigma are the standard deviation.
Random.vonmisesvariate(
mu,
kappa )
Mu is the mean angle, expressed in radians between 0 and-a-pi, and Kappa is the concentration parameter, which must is greater than or equal to zero. If Kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 topi.
Random.paretovariate(
Alpha )
Pareto distribution. Alpha is the shape parameter.
Random.weibullvariate(
Alpha,
beta )
Weibull distribution. Alpha is the scale parameter and Beta is the shape parameter.
Alternative Generator:
class Random.Systemrandom([
seed])
Class that uses theos.urandom ()function for generating random numbers from sources provided by the operating Sy Stem. Not available on all systems. Does not rely in software state, and sequences is not reproducible. Accordingly, theSeed ()method has a no effect and is ignored. Thegetstate ()andSetState ()methods raisenotimplementederrorif called.
See Also
M. Matsumoto and T. Nishimura, "Mersenne twister:a 623-dimensionally equidistributed uniform pseudorandom number Generato R ", ACM transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3-30 1998.
Complementary-multiply-with-carry recipe for a compatible alternative random number generator with a long period and compa ratively Simple update operations.
9.6.1. Notes on reproducibility
Sometimes it is useful to being able to reproduce the sequences given by a pseudo random number generator. By re-using a seed value, the same sequence should is reproducible from run to run as long as multiple threads is not run Ning.
Most of the random module ' s algorithms and seeding functions is subject to change across Python versions, but the other aspects is guaranteed not to change:
- If a new seeding method is added and then a backward compatible seeder would be offered.
- The generator ' srandom ()method would continue to produce the same sequence when the compatible seeder was given th E same seed.
9.6.2. Examples and Recipes
Basic usage:
>>> random.random() # Random float x, 0.0 <= x < 1.0 0.37444887175646646 >>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0 1.1800146073117523 >>> random.randrange(10) # Integer from 0 to 9 7 >>> random.randrange(0, 101, 2) # Even integer from 0 to 100 26 >>> random.choice(‘abcdefghij‘) # Single random element ‘c‘ >>> items = [1, 2, 3, 4, 5, 6, 7] >>> random.shuffle(items) >>> items [7, 3, 2, 5, 6, 4, 1] >>> random.sample([1, 2, 3, 4, 5], 3) # Three samples without replacement [4, 1, 5]
A common task is to make arandom.choice ()with weighted probabilities.
If The weights is small an integer ratios, a simple technique was to build a sample population with repeats:
A more general approach are to arrange the weights in a cumulative distribution withitertools.accumulate (), and T Hen locate the random value withbisect.bisect ():
Python Standard library 3.4.3-random