Numbers 3.6.2

  1. Numbers 36 1-13
  2. Numbers 3.6.2 Download
  3. Numbers 3 6 9

R-3.6.2 for Windows (32/64 bit) Download R 3.6.2 for Windows (83 megabytes, 32/64 bit) Installation and other instructions; New features in this version. Learn more about creating, importing, editing, exporting, printing and sharing sophisticated spreadsheets. Learn more with these Numbers resources.

Source code:Lib/random.py

Crate playlists easily. Thanks to Playlist. All numbers on the number line— even those that are not rational—can be approximated by finite decimals. For example, the number is approximately 1.41421. Expanding the rational number system to include all numbers on the number line brings you to the real number system. Finite decimals give you access to arbitrarily accurate approximate. '(3 - 5), (5 - 3), (6 - 2), (7 - 3)' In Choose odd Number Pair / Group, certain pairs / groups of numbers are given out of which all except one are similar in some manner while one is different. The numbers in these similar pairs may have the same property or may be related to each other according to the same rule. The candidate is required to choose the odd pair / group.

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 random(), 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 random.Random class. You can instantiate your owninstances of Random to get generators that don’t share state.

Class Random 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 randrange() to produce selections over an arbitrarily large range.

The random module also provides the SystemRandom class whichuses the system function os.urandom() to generate random numbersfrom sources provided by the operating system.

Warning

The pseudo-random generators of this module should not be used forsecurity purposes. For security or cryptographic uses, see thesecrets module.

See also

M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionallyequidistributed uniform pseudorandom number generator”, ACM Transactions onModeling and Computer Simulation Vol. 8, No. 1, January pp.3–30 1998.

Complementary-Multiply-with-Carry recipe for a compatible alternativerandom number generator with a long period and comparatively simple updateoperations.

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 os.urandom() function for detailson availability).

If a is an int, it is used directly.

With version 2 (the default), a str, bytes, or bytearrayobject gets converted to an int and all of its bits are used.

With version 1 (provided for reproducing random sequences from older versionsof Python), the algorithm for str and bytes 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.

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 internal state of the generator. Thisobject can be passed to setstate() to restore the state.

random.setstate(state)

state should have been obtained from a previous call to getstate(), andsetstate() restores the internal state of the generator to what it was atthe time getstate() was called.

Functions for bytes¶

random.randbytes(n)

Generate n random bytes.

This method should not be used for generating security tokens.Use secrets.token_bytes() instead.

Functions for integers¶

random.randrange(stop)
random.randrange(start, stop[, step])

Return a randomly selected element from range(start,stop,step). This isequivalent to choice(range(start,stop,step)), but doesn’t actually build arange object.

The positional argument pattern matches that of range(). Keyword argumentsshould not be used because the function may use them in unexpected ways.

3.6.2

Changed in version 3.2: randrange() is more sophisticated about producing equally distributedvalues. Formerly it used a style like int(random()*n) which could produceslightly uneven distributions.

random.randint(a, b)

Return a random integer N such that a<=N<=b. Alias forrandrange(a,b+1).

random.getrandbits(k)

Returns a non-negative Python integer with k random bits. This methodis supplied with the MersenneTwister generator and some other generatorsmay also provide it as an optional part of the API. When available,getrandbits() enables randrange() to handle arbitrarily largeranges.

Changed in version 3.9: This method now accepts zero for k.

Functions for sequences¶

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty,raises IndexError.

random.choices(population, weights=None, *, cum_weights=None, k=1)

Return a k sized list of elements chosen from the population with replacement.If the population is empty, raises IndexError.

If a weights sequence is specified, selections are made according to therelative weights. Alternatively, if a cum_weights sequence is given, theselections are made according to the cumulative weights (perhaps computedusing itertools.accumulate()). For example, the relative weights[10,5,30,5] are equivalent to the cumulative weights[10,15,45,50]. Internally, the relative weights are converted tocumulative weights before making selections, so supplying the cumulativeweights saves work.

Numbers 36 1-13

If neither weights nor cum_weights are specified, selections are madewith equal probability. If a weights sequence is supplied, it must bethe same length as the population sequence. It is a TypeErrorto specify both weights and cum_weights.

The weights or cum_weights can use any numeric type that interoperateswith the float values returned by random() (that includesintegers, floats, and fractions but excludes decimals). Behavior isundefined if any weight is negative. A ValueError is raised if allweights are zero.

Numbers 36 1-13

For a given seed, the choices() function with equal weightingtypically produces a different sequence than repeated calls tochoice(). The algorithm used by choices() uses floatingpoint arithmetic for internal consistency and speed. The algorithm usedby choice() defaults to integer arithmetic with repeated selectionsto avoid small biases from round-off error.

Changed in version 3.9: Raises a ValueError if all weights are zero.

random.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 random().

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.

Deprecated since version 3.9, will be removed in version 3.11: The optional parameter random.

random.sample(population, k, *, counts=None)

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 hashable or unique. If the populationcontains repeats, then each occurrence is a possible selection in the sample.

Repeated elements can be specified one at a time or with the optionalkeyword-only counts parameter. For example, sample(['red','blue'],counts=[4,2],k=5) is equivalent to sample(['red','red','red','red','blue','blue'],k=5).

To choose a sample from a range of integers, use a range() 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, a ValueErroris raised.

Changed in version 3.9: Added the counts parameter.

Deprecated since version 3.9: In the future, the population must be a sequence. Instances ofset are no longer supported. The set must first be convertedto a list or tuple, preferably in a deterministicorder so that the sample is reproducible.

Real-valued distributions¶

The 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.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 that a<=N<=b fora<=b and b<=N<=a for b<a.

The end-point value b may or may not be included in the rangedepending on floating-point rounding in the equation a+(b-a)*random().

random.triangular(low, high, mode)

Return a random floating point number N such that low<=N<=high andwith the specified mode between those bounds. The low and high boundsdefault to zero and one. The mode argument defaults to the midpointbetween the bounds, giving a symmetric distribution.

Numbers 3.6.2 Download

random.betavariate(alpha, beta)

Beta distribution. Conditions on the parameters are alpha>0 andbeta>0. Returned values range between 0 and 1.

random.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.

random.gammavariate(alpha, beta)

Gamma distribution. (Not the gamma function!) Conditions on theparameters are alpha>0 and beta>0.

The probability distribution function is:

random.gauss(mu, sigma)

Gaussian distribution. mu is the mean, and sigma is the standarddeviation. This is slightly faster than the normalvariate() functiondefined below.

Multithreading note: When two threads call this functionsimultaneously, it is possible that they will receive thesame return value. This can be avoided in three ways.1) Have each thread use a different instance of the randomnumber generator. 2) Put locks around all calls. 3) Use theslower, but thread-safe normalvariate() function instead.

random.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.

random.normalvariate(mu, sigma)

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

random.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.

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 shapeparameter.

Alternative Generator¶

class random.Random([seed])

Class that implements the default pseudo-random number generator used by therandom module.

Deprecated since version 3.9: In the future, the seed must be one of the following types:NoneType, int, float, str,bytes, or bytearray.

class random.SystemRandom([seed])

Class that uses the os.urandom() function for generating random numbersfrom sources provided by the operating system. Not available on all systems.Does not rely on software state, and sequences are not reproducible. Accordingly,the seed() method has no effect and is ignored.The getstate() and setstate() methods raiseNotImplementedError if called.

Notes on Reproducibility¶

Sometimes it is useful to be able to reproduce the sequences given by apseudo-random 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.

Examples¶

Basic examples:

Simulations:

Example of statistical bootstrapping using resamplingwith replacement to estimate a confidence interval for the mean of a sample:

Numbers 3 6 9

Example of a resampling permutation testto determine the statistical significance or p-value of an observed differencebetween the effects of a drug versus a placebo:

Simulation of arrival times and service deliveries for a multiserver queue:

See also

Statistics for Hackersa video tutorial byJake Vanderplason statistical analysis using just a few fundamental conceptsincluding simulation, sampling, shuffling, and cross-validation.

Economics Simulationa simulation of a marketplace byPeter Norvig that shows effectiveuse of many of the tools and distributions provided by this module(gauss, uniform, sample, betavariate, choice, triangular, and randrange).

A Concrete Introduction to Probability (using Python)a tutorial by Peter Norvig coveringthe basics of probability theory, how to write simulations, andhow to perform data analysis using Python.

Recipes¶

The default random() returns multiples of 2⁻⁵³ in the range0.0 ≤ x < 1.0. All such numbers are evenly spaced and are exactlyrepresentable as Python floats. However, many other representablefloats in that interval are not possible selections. For example,0.05954861408025609 isn’t an integer multiple of 2⁻⁵³.

The following recipe takes a different approach. All floats in theinterval are possible selections. The mantissa comes from a uniformdistribution of integers in the range 2⁵² ≤ mantissa < 2⁵³. Theexponent comes from a geometric distribution where exponents smallerthan -53 occur half as often as the next larger exponent.

All real valued distributionsin the class will use the new method:

The recipe is conceptually equivalent to an algorithm that chooses fromall the multiples of 2⁻¹⁰⁷⁴ in the range 0.0 ≤ x < 1.0. All suchnumbers are evenly spaced, but most have to be rounded down to thenearest representable Python float. (The value 2⁻¹⁰⁷⁴ is the smallestpositive unnormalized float and is equal to math.ulp(0.0).)

See also

Generating Pseudo-random Floating-Point Values apaper by Allen B. Downey describing ways to generate morefine-grained floats than normally generated by random().