random number generator
random ( random)Create pseudo-random numbers
Code source: Lib/random.py
The module implementspseudoThis module implements pseudo random number generators for different distributions.
For integers, there is a uniform selection from a range. For sequences, there's a uniform selection of the randomelement and the function that can generate a randompermutation of a list in-place, and a function for random sampling that does not require replacement.
On the actual line, there exist functions to calculate uniform, normal (Gaussian), lognormal, negative exponential beta, and gamma distributions. In order to generate distributions of angles, you can use von Mises Distribution is readily available.
Most modulefunctions depend on the basic modulefunction random() that generates a randomfloat with a uniform semi-open spectrum [0.0, 1.0). Python uses its Mersenne Twister as the core generator. It produces 53-bit precision floats and runs for 2**19937-1. The code used in C is both speedy and threadsafe. It is thread-safe and fast. Mersenne Twister is one of the most extensively examined random number generators in existence. However, being completely determinate, it's not suitable for all applications, and is completely unsuitable for cryptographic uses.
The functions in this module are bound methods of a hidden instance of the random. Randomclass. It is possible to instantiate your own versions for Random for generators that aren't sharing state.
Class Random can be subclassed as well if you would like to employ a different basic generator of your own devising: in that case, modify any of the random() (), seed() getstate(), as well as the setstate() method. A new generator can include a getrandbits() method -- this permits randrange() to produce the random numbers over an infinitely large range.
The random module additionally provides also the SystemRandom class, which utilizes the system function os.urandom() to generate random numbers from the sources supplied through the operating system.
Warning
The pseudo-random generators that comprise this module are not suitable for security reasons. For cryptographic or security-related uses look up 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 omitted or None otherwise, the currently running system's clock time utilized. If randomness sources are available to the operating system system, then they will be used in place of using the current system clock (see for the os.urandom() function for information about availability).
If it is an integer, it is used directly.
In version 2, (the default) the str, bytes as well as a bytearray object is transformed into an int and all its bits are utilized.
Version 1 (provided to reproduce random sequences from earlier versions of Python) The method that is used to compute str and bytes generates a narrower range of seeds.
Modified to Version 3.2:Moved to the version 2 scheme which makes use of all the bits in 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()
A return object that captures the current internal current state for 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 findstate(), and setstate() restores the internal state of the generator to the state it was at the time when getstate() was called.
Functions for bytes
random. randbytes( n)
Generate the number of 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 a randomly selected element from range(start stopping, step). It's similar to choice(range(start stopping, start step)), but does not actually create an object of range.
The positional argument pattern matches the format of range(). Keyword arguments should not be used, as the function might use them in unintended ways.
Updated since Version 3.2: randrange() is more sophisticated in producing equally distributed values. Before, it employed the style of int(random()*n) which might result in slightly uneven distributions.
It is no longer supported as of Version 3.10: The automatic conversion of non-integer type types to equivalent integers is no longer supported. Currently randrange(10.0) is lostlessly converted to randrange(10). In the near future, this will raise a "TypeError".
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 an random numbers N in a way that a <= N <= B. Alias for randrange(a, b+1).random.getrandbits(k)
Returns a non-negative Python integer that contains k random bits. This method is included in the MersenneTwister generator and a few other generators may also provide it as an optional part within the 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 the random part of the non-empty sequence seq. If seq is empty, raises IndexError.random.choices(population, weights=None, *, cum_weights=None, k=1)
Return the k size list of elements selected to be included in the population with replacement. In case the sample is not full, it is raised IndexError.
If a weights sequence is specified, selections are made in accordance with the weights in relation to the. 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 weights relative to [10, 5 30, 5and 30] equal to the total weights [10 15, 45, 50respectively. Internally those weights can be transformed to cumulative weights before making decisions by supplying the cumulative weights saves work.
If there is no weights or cum_weights are specified, selections are made with equal probability. If a weights series is supplied, it must have exactly the same length as the number of people in the sequence. It's a kind of error to provide that both cum_weights together with cum_weights.
Weights or cum_weights the weights and cum_weights are able to use any numerical type that is compatible with the float results returned in random() (that includes integers and floats as well as fractions, but does not include decimals). Weights are assumed to be non-negative and finite. The ValueError is raised if the weights all are null.
For a given seed, you can use the selection() function with equal weighting usually results in distinct sequences than repeatedly calling choice(). The algorithm used by the choice() uses floating point arithmetic to ensure internal stability and speed. The algorithm used to calculate the choice() defaults to the integer method of arithmetic and repeats selections to minimize small variations due to round off error.
New Version 3.6.
Changed in version 3.9: Raises a ValueError if all weights are zero.random.shuffle(x[, random])
The sequence is shuffled x in place.
The optional argument random can be an 0-argument function that returns the random floating value in [0.0, 1.0); by default, it functions as random().
To shuffle an immutable sequence and return a new to be shuffled, make use of sample(x, k=len(x)) instead.
Be aware that even for tiny len(x), the total number of possible permutations of x can quickly grow larger than the length of time of most random number generators. That means that the vast majority of permutations for a long sequence will never be produced. For example, a sequence that's length 2080 is the largest that can fit into the space of the 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 an length list of k length listing of unique elements that were selected from the sample sequence or set. Used for random sampling, without replacement.
The result is a list that contains elements of the population, while leaving the original population unchanged. The resultant list is ordered in a selection order, which means that all sub-slices are also constitute valid random samples. This allows winners of raffles (the the sample) to be split into grand prize winners and second place winners (the subslices).
The population members need not be unique or hashable. If the population contains repeats every occurrence of possibly a possibility of selection in the sample.
Repeated elements can be specified one at a time or via the optional Keyword-only counting parameter. For instance, sample(['red', 'blue'], counts=[4 2] 5, k=5) is equivalent to sample(['red', 'red', 'red' blue','red", "blue'count=[4, 2], k=5).
To select a sample from an array of integers employ a range() 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 greater than the total population size, the ValueError is raised.
Updated in version 3.9:Added the counts parameter.
No longer supported since version 3.9: In the future, the population must be a series. Instances in the form of sets are no longer supported. The set first needs to be converted to an list or tuple or tuple, and preferably in the same order to ensure that the sample is reproducible.
Real-valued distributions
The following functions create specific real-valued distributions. Function parameters are named in honor of their respective variables in the equation for the distribution, as commonly used in mathematical practices The majority of these equations can be found within any text on 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 number N that is N = a= b for a <= b and b= N <+ b = < the value of.
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 such that low= N <= high and in the specified mode between those bounds. It is assumed that the Low and high bounds are set 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 are beta > and 0 as well as beta > zero. Returned values range between 0 and 1.random.expovariate(lambd)
Exponential distribution. lambd is 1.0 divided by the desired mean. It must be not zero. (The parameter could be called "lambda", but that is a reserved word 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 function of gamma!) The parameters must be in the range of beta > 0. as well as beta > zero.
Probability distribution functions:
Notes on Reproducibility
Sometimes it is useful to be able to reproduce the sequences given by a pseudo-random generator. If you reuse a seed number, the same sequence should be able to be reproduced from run to running as long as several threads are not running.
The majority of the random module's algorithms and seeding functions are susceptible to change across Python versions, however two elements are guaranteed not to remain the same:
- If a new seeding method is introduced, a backward compatible seeder will be provided.
-
A generator's
random()method will produce the same sequence when the suitable seeder is provided with the same seed.
Comments
Post a Comment