random number generator
random --- Generate pseudo-random numbers
The source code is Lib/random.py
This module implementspseudoThis module implements pseudo random number generators for various distributions.
For integers, there is a uniform selection of a range. For sequences there is uniform selection of the randomelement which is it is a method to generate a randompermutation of a set in-place as well as a function that allows random sampling without replacing.
On the actual line, there are tools to calculate normal, uniform (Gaussian), positive exponential, lognormal, beta, and gamma. For generating distributions of angles, that of the von Mises distributive is accessible.
Nearly all modulefunctions All modulefunctions rely on the basic routine random()
, which generates a randomfloat evenly across the semi-open range [0.0, 1.0). Python employs it's Mersenne Twister as the core generator. It creates floats with 53 bits of precision with a length of 2**19937-1. The underlying implementation in C is both efficient and thread-safe. It is thread-safe and fast. Mersenne Twister is one of the most extensively researched random number generators in existence. However, being completely dependent, it isn't suitable for all applications and is not suitable for cryptographic purposes.
The functions supplied by this module are bound methods that are a secret example of random.
Random
class. You can instantiate your own versions of Random
to generate generators that do not share state.
Class Random could also be subclassed if need to use a new base generator from your own invention In that case, replace these methods to override the random() (), seed(), getstate(), as well as getstate(), setstate() techniques. Optionally, a new generator can supply an acquirerandbits()
method -this permits randrange()
to produce choices over an arbitrarily wide range.
The random
module additionally offers the SystemRandom
class that makes use of functions in the operating system os.urandom()
to create random numbers from data sources provided to the OS.
Warning
The pseudo-random generators in this module are not suitable to create security measures. For cryptographic or security-related uses refer to the secrets
module.
Also see
M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator", 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 comparatively simple update operations.
Bookkeeping functions
random.seed(a=None, version=2)
Initialize the random number generator.
If an option is left out or If none
If none is specified, the currently running system's clock time used. If randomness sources are available through the OS, these sources are used instead of using the current system clock (see for the os.urandom()
function for information about availability).
If you are using a is an int, it is directly used.
With version two (the default) with version 2, a str
, bytes
, or bytearray
object is converted into an int
and all its bits are utilized.
Version 1 (provided for reproducing random sequences from earlier versions of Python) the process of str
and bytes
generates a narrower range of seeds.
changed with version 3.2:Moved to the version 2 scheme that utilizes all the bits of a string seed.
Deprecated since version 3.9: In the future, the seed must be one of the following types: NoneType, int, float, str, bytes, or bytearray.random.getstate()
Return an object capturing the current status of the generator. This object can be passed to setstate()
to restore the state.random.setstate
(state)
state could have come by a previous call to getstate()
, and setstate()
restores the internal state of the generator to what it was at the time the call to getstate()
was called.
Functions for bytes
random.
randbytes
( n)
Generate N random bits.
This method should not be used to create security tokens. Use secrets.token_bytes()
instead.
New in version 3.9.
Functions for integers
random.randrange(stop)random.randrange(start, stop[, step])
Return an element randomly selected from range(start stopping, step)
. This is the same as choice(range(start stop step))
, but does not actually create an object of range.
The pattern of arguments for positions is similar to the one used by range()
. Keyword arguments shouldn't be used as the function might use them in unintended ways.
Modified with Version 3.2: randrange()
is more sophisticated in producing equally distributed values. Before, it employed the same style as int(random()*n)
which might result in slightly uneven distributions.
Refused since the version 3.10: The automatic conversion of non-integer numbers to equivalent integers is now no longer required. Currently randrange(10.0)
is losslessly converted to randrange(10)
. In the future this could cause a Error in Type
.
Deprecated since version 3.10: The exception raised for non-integral values such as randrange(10.5) or randrange('10') will be changed from ValueError to TypeError.random.randint(a, b)
Return a random number N with the number a is greater than <= the value of
. Alias for randrange(a, b+1).random.getrandbits(k)
Returns a non-negative Python integer with the number of random bits. This method is supplied with the MersenneTwister generator and other generators might also offer it as an additional feature that is part of their API. If it is available, the getrandbits()
enables randrange()
to handle huge ranges of arbitrarily wide sizes.
Updated to Version 3.9:This method now accepts zero for k.
Sequences are a sequence of functions.
random.
selection
( seq)
Return a random value from the non-empty sequence seq. If seq is empty, raises IndexError.random.choices(population, weights=None, *, cum_weights=None, k=1)
Return an K size list of elements selected from the population with replacement. In the event that populace is not filled, the program raises indexError
.
If a weights sequence is specified, choices are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()
). For instance, the relative weights [10, 5 30-5and 30]
are equivalent to the cumulative weights [10 15, 45, 50respectively
. Internally they are transformed to cumulative weights prior to making choices thus providing the cumulative weights will save time.
If neither weights nor cum_weights are given, then selections can be made with equal likelihood. If a weights sequence has been specified, it must be the same length as the population sequence. It is a MethodError
to indicate that both the weights in addition to cum_weights.
The weighs are also called cum_weights. cum_weights can be made using any numeric type that interacts with floating
values generated from random()
(that includes integers, floats, and fractions, but excludes decimals). Weights are presumed to be not negative and are finite. The ValueError
is raised when there are no weights.
For a specific seed, you can use the selection()
function with equal weighting will typically produce distinct sequences than multiple calls made to choices()
. The algorithm used by choices()
uses floating point arithmetic for internal reliability and speed. The algorithm used to calculate choice()
defaults to the integer method of arithmetic and repeats selections in order to avoid slight errors due to round-off errors.
New Version 3.6.
Changed in version 3.9: Raises a ValueError if all weights are zero.random.shuffle(x[, random])
Shuffle the sequence by x to ensure.
The argument is optional. random could be an 0-argument function that returns an random floating value in [0.0, 1.0); by default, this is the function random()
.
To move an immutable list and return a fresh shuffled list, use sample(x, k=len(x))
instead.
It is important to note that even for small len(x)
, the total number or permutations of the sequence can quickly grow larger than the range of random number generators. This means that the majority of permutations of a long sequence can never be created. For instance, a sequence of 2080 characters is one of the longest sequences that fit inside the timeframe that is the duration of Mersenne Twister random number generator.
Deprecated since version 3.9, will be removed in version 3.11: The optional parameter random.random.sample(population, k, *, counts=None)
Return a length list of k length listing of unique elements that were selected from the population sequence or set. Used for random sampling with no replacement.
It returns a new list with elements from the population while remaining the original population as is. The resultant list is in order of selection, so that all sub-slices will remain valid random samples. This allows the raffle winners (the samples) to be divided into grand prize winners and second prize winner (the subslices).
The individuals in the population should not be unique or hashable. If the population has repeated instances the occurrences are one of the possible selections in the sample.
Repeated elements may be specified one at a time or with the optional only keyword count parameter. For instance, sample(['red', 'blue'], counts=[4 2] and k=5)
is equivalent to sample(['red','red",'red 'red', 'blue", "blue'5, k=5)
.
For selecting a sample of an array of integers, utilize an interval()
object as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), k=60)
.
If the sample size is larger than the population size, an ValueError
is raised.
Updated in version 3.9:Added the counts parameter.
The format is no longer supported as of version 3.9: In the future, the population has to be a sequential. Instances within a set
are no longer supported. The set has to first be converted to it's own listing
or tuple
, preferably in a deterministic order so that the sample is reproducible.
Real-valued distributions
The following functions generate specific real-valued distributions. The parameters of the function are named after those variables within the equation for the distribution, as they are used in everyday mathematical practice These formulas can be found in any text in statistics. 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 N with an N= b, for a= b and b= Nis a. < an.
The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) * random().random.triangular(low, high, mode)
Return an random floating-point number N which is low <= N <= high
and in the specified modus between these limits. This is because 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 for the parameters are alpha > 0,
and beta > 0
. Returned values range between 0 and 1.random.
expovariate
(lambd)
Exponential distribution. lambd is 1.0 divided by the desired median. It must be not zero. (The parameter is referred to as "lambda", but that is a reserved term that is not used by Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.random.gammavariate(alpha, beta)
Gamma distribution. ( Not the gamma function!) The parameters must be in the range of beta > 0
and beta > 0.
.
Its probability distribution feature is:
Notes on Reproducibility
Sometimes it's important in order to reproduce the sequences produced by a pseudo-random number generator. Re-using a seed's value, the same sequence should be reproducible from one run to the next the next, as long as there are no multiple threads aren't running.
The majority of random module's algorithms and seeding functions are susceptible to changes across Python versions, however two aspects are guaranteed not to remain the same:
- If a new method of seeding is introduced, a backward compatible seeder will be offered.
-
The generator's
random()
method will continue to produce the same sequence if a compatible observer is given the same seed.
Comments
Post a Comment