Python defines a set of functions that are used to generate or manipulate random numbers. This particular type of functions are used in a lot of games, lotteries. The standard random module implements a random number generator. Usage is simple: import random print random.random. This prints a random floating.
— Generate pseudo-random numbersSource code:This module implements pseudo-random number generators for variousdistributions.For integers, there is uniform selection from a range. For sequences, there isuniform selection of a random element, a function to generate a randompermutation of a list in-place, and a function for random sampling withoutreplacement.On the real line, there are functions to compute uniform, normal (Gaussian),lognormal, negative exponential, gamma, and beta distributions. For generatingdistributions of angles, the von Mises distribution is available.Almost all module functions depend on the basic function, whichgenerates a random float uniformly in the semi-open range 0.0, 1.0).
Pythonuses the Mersenne Twister as the core generator. It produces 53-bit precisionfloats and has a period of 2.19937-1. The underlying implementation in C isboth fast and threadsafe.
The Mersenne Twister is one of the most extensivelytested random number generators in existence. However, being completelydeterministic, it is not suitable for all purposes, and is completely unsuitablefor cryptographic purposes.The functions supplied by this module are actually bound methods of a hiddeninstance of the class. You can instantiate your owninstances of to get generators that don’t share state.Class can also be subclassed if you want to use a differentbasic generator of your own devising: in that case, override the random,seed, getstate, and setstate methods.Optionally, a new generator can supply a getrandbits method — thisallows to produce selections over an arbitrarily large range.The module also provides the class whichuses the system function to generate random numbersfrom sources provided by the operating system.
Bookkeeping functions random. Seed ( a=None, version=2 )Initialize the random number generator.If a is omitted or None, the current system time is used. Ifrandomness sources are provided by the operating system, they are usedinstead of the system time (see the function for detailson availability).If a is an int, it is used directly.With version 2 (the default), a, orobject gets converted to an and all of its bits are used.With version 1 (provided for reproducing random sequences from older versionsof Python), the algorithm for and generates anarrower range of seeds. Changed in version 3.2: Moved to the version 2 scheme which uses all of the bits in a string seed. Getstate ( )Return an object capturing the current internal state of the generator. Thisobject can be passed to to restore the state.
Setstate ( state )state should have been obtained from a previous call to, andrestores the internal state of the generator to what it was atthe time was called. Getrandbits ( k )Returns a Python integer with k random bits. This method is supplied withthe MersenneTwister generator and some other generators may also provide itas an optional part of the API. When available, enablesto handle arbitrarily large ranges. Functions for sequences random.
Choice ( seq )Return a random element from the non-empty sequence seq. If seq is empty,raises.
Choices ( population, weights=None,., cumweights=None, k=1 )Return a k sized list of elements chosen from the population with replacement.If the population is empty, raises.If a weights sequence is specified, selections are made according to therelative weights. Alternatively, if a cumweights sequence is given, theselections are made according to the cumulative weights (perhaps computedusing ). For example, the relative weights10, 5, 30, 5 are equivalent to the cumulative weights10, 15, 45, 50. Internally, the relative weights are converted tocumulative weights before making selections, so supplying the cumulativeweights saves work.If neither weights nor cumweights are specified, selections are madewith equal probability. If a weights sequence is supplied, it must bethe same length as the population sequence. It is ato specify both weights and cumweights.The weights or cumweights can use any numeric type that interoperateswith the values returned by (that includesintegers, floats, and fractions but excludes decimals).For a given seed, the function with equal weightingtypically produces a different sequence than repeated calls to. The algorithm used by uses floatingpoint arithmetic for internal consistency and speed.
![Python Python](/uploads/1/2/5/3/125361812/223316065.jpg)
The algorithm usedby defaults to integer arithmetic with repeated selectionsto avoid small biases from round-off error. New in version 3.6.
Shuffle ( x , random )Shuffle the sequence x in place.The optional argument random is a 0-argument function returning a randomfloat in 0.0, 1.0); by default, this is the function.To shuffle an immutable sequence and return a new shuffled list, usesample(x, k=len(x)) instead.Note that even for small len(x), the total number of permutations of xcan quickly grow larger than the period of most random number generators.This implies that most permutations of a long sequence can never begenerated. For example, a sequence of length 2080 is the largest thatcan fit within the period of the Mersenne Twister random number generator.
Sample ( population, k )Return a k length list of unique elements chosen from the population sequenceor set. Used for random sampling without replacement.Returns a new list containing elements from the population while leaving theoriginal population unchanged. The resulting list is in selection order so thatall sub-slices will also be valid random samples. This allows raffle winners(the sample) to be partitioned into grand prize and second place winners (thesubslices).Members of the population need not be or unique. If the populationcontains repeats, then each occurrence is a possible selection in the sample.To choose a sample from a range of integers, use a object as anargument. This is especially fast and space efficient for sampling from a largepopulation: sample(range(10000000), k=60).If the sample size is larger than the population size, ais raised. Real-valued distributionsThe following functions generate specific real-valued distributions.
Functionparameters are named after the corresponding variables in the distribution’sequation, as used in common mathematical practice; most of these equations canbe found in any statistics text. Random ( )Return the next random floating point number in the range 0.0, 1.0). Uniform ( a, b )Return a random floating point number N such that a 0 andbeta 0. Returned values range between 0 and 1. Expovariate ( lambd )Exponential distribution.
Lambd is 1.0 divided by the desiredmean. It should be nonzero. (The parameter would be called“lambda”, but that is a reserved word in Python.) Returned valuesrange from 0 to positive infinity if lambd is positive, and fromnegative infinity to 0 if lambd is negative.
Gammavariate ( alpha, beta )Gamma distribution. ( Not the gamma function!) Conditions on theparameters 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 random. Gauss ( mu, sigma )Gaussian distribution. Mu is the mean, and sigma is the standarddeviation.
This is slightly faster than the functiondefined below. Lognormvariate ( mu, sigma )Log normal distribution. If you take the natural logarithm of thisdistribution, you’ll get a normal distribution with mean mu and standarddeviation sigma. Mu can have any value, and sigma must be greater thanzero. Normalvariate ( mu, sigma )Normal distribution. Mu is the mean, and sigma is the standard deviation. Vonmisesvariate ( mu, kappa )mu is the mean angle, expressed in radians between 0 and 2.
pi, and kappais the concentration parameter, which must be greater than or equal to zero. Ifkappa is equal to zero, this distribution reduces to a uniform random angleover the range 0 to 2. pi.
Paretovariate ( alpha )Pareto distribution. Alpha is the shape parameter.
Weibullvariate ( alpha, beta )Weibull distribution. Alpha is the scale parameter and beta is the shapeparameter. Notes on ReproducibilitySometimes it is useful to be able to reproduce the sequences given by a pseudorandom number generator. By re-using a seed value, the same sequence should bereproducible from run to run as long as multiple threads are not running.Most of the random module’s algorithms and seeding functions are subject tochange across Python versions, but two aspects are guaranteed not to change:.If a new seeding method is added, then a backward compatible seeder will beoffered.The generator’s random method will continue to produce the samesequence when the compatible seeder is given the same seed.
random # Random float: 0.0 uniform ( 2.5, 10.0 ) # Random float: 2.5 expovariate ( 1 / 5 ) # Interval between arrivals averaging 5 seconds 5.65031 randrange ( 10 ) # Integer from 0 to 9 inclusive 7 randrange ( 0, 101, 2 ) # Even integer from 0 to 100 inclusive 26 choice ( 'win', 'lose', 'draw' ) # Single random element from a sequence 'draw' deck = 'ace two three four'. Split shuffle ( deck ) # Shuffle a list deck 'four', 'two', 'ace', 'three' sample ( 10, 20, 30, 40, 50 , k = 4 ) # Four samples without replacement 40, 10, 50, 30Simulations. # Six roulette wheel spins (weighted sampling with replacement) choices ( 'red', 'black', 'green' 18, 18, 2 , k = 6 ) 'red', 'green', 'black', 'black', 'red', 'black' # Deal 20 cards without replacement from a deck of 52 playing cards # and determine the proportion of cards with a ten-value # (a ten, jack, queen, or king). deck = collections. Counter ( tens = 16, lowcards = 36 ) seen = sample ( list ( deck. Elements ), k = 20 ) seen.
Count ( 'tens' ) / 20 0.15 # Estimate the probability of getting 5 or more heads from 7 spins # of a biased coin that settles on heads 60% of the time. def trial.
Return choices ( 'HT', cumweights = ( 0.60, 1.00 ), k = 7 ). Count ( 'H' ) = 5. sum ( trial for i in range ( 10000 )) / 10000 0.4169 # Probability of the median of 5 samples being in middle two quartiles def trial. Return 2500 sum ( trial for i in range ( 10000 )) / 10000 0.7958Example of using resamplingwith replacement to estimate a confidence interval for the mean of a sample ofsize five.