summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Frandom.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/library%2Frandom.html')
-rw-r--r--devdocs/python~3.12/library%2Frandom.html248
1 files changed, 248 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Frandom.html b/devdocs/python~3.12/library%2Frandom.html
new file mode 100644
index 00000000..d2c479eb
--- /dev/null
+++ b/devdocs/python~3.12/library%2Frandom.html
@@ -0,0 +1,248 @@
+ <span id="random-generate-pseudo-random-numbers"></span><h1>random — Generate pseudo-random numbers</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/random.py">Lib/random.py</a></p> <p>This module implements pseudo-random number generators for various distributions.</p> <p>For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.</p> <p>On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.</p> <p>Almost all module functions depend on the basic function <a class="reference internal" href="#random.random" title="random.random"><code>random()</code></a>, which generates a random float uniformly in the half-open range <code>0.0 &lt;= X &lt; 1.0</code>. 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 is completely unsuitable for cryptographic purposes.</p> <p>The functions supplied by this module are actually bound methods of a hidden instance of the <a class="reference internal" href="#random.Random" title="random.Random"><code>random.Random</code></a> class. You can instantiate your own instances of <a class="reference internal" href="#random.Random" title="random.Random"><code>Random</code></a> to get generators that don’t share state.</p> <p>Class <a class="reference internal" href="#random.Random" title="random.Random"><code>Random</code></a> can also be subclassed if you want to use a different basic generator of your own devising: see the documentation on that class for more details.</p> <p>The <a class="reference internal" href="#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code>random</code></a> module also provides the <a class="reference internal" href="#random.SystemRandom" title="random.SystemRandom"><code>SystemRandom</code></a> class which uses the system function <a class="reference internal" href="os#os.urandom" title="os.urandom"><code>os.urandom()</code></a> to generate random numbers from sources provided by the operating system.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the <a class="reference internal" href="secrets#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code>secrets</code></a> module.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>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.</p> <p><a class="reference external" href="https://code.activestate.com/recipes/576707/">Complementary-Multiply-with-Carry recipe</a> for a compatible alternative random number generator with a long period and comparatively simple update operations.</p> </div> <section id="bookkeeping-functions"> <h2>Bookkeeping functions</h2> <dl class="py function"> <dt class="sig sig-object py" id="random.seed">
+<code>random.seed(a=None, version=2)</code> </dt> <dd>
+<p>Initialize the random number generator.</p> <p>If <em>a</em> is omitted or <code>None</code>, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the <a class="reference internal" href="os#os.urandom" title="os.urandom"><code>os.urandom()</code></a> function for details on availability).</p> <p>If <em>a</em> is an int, it is used directly.</p> <p>With version 2 (the default), a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>, or <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> object gets converted to an <a class="reference internal" href="functions#int" title="int"><code>int</code></a> and all of its bits are used.</p> <p>With version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> and <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> generates a narrower range of seeds.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Moved to the version 2 scheme which uses all of the bits in a string seed.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The <em>seed</em> must be one of the following types: <code>None</code>, <a class="reference internal" href="functions#int" title="int"><code>int</code></a>, <a class="reference internal" href="functions#float" title="float"><code>float</code></a>, <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>, or <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.getstate">
+<code>random.getstate()</code> </dt> <dd>
+<p>Return an object capturing the current internal state of the generator. This object can be passed to <a class="reference internal" href="#random.setstate" title="random.setstate"><code>setstate()</code></a> to restore the state.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.setstate">
+<code>random.setstate(state)</code> </dt> <dd>
+<p><em>state</em> should have been obtained from a previous call to <a class="reference internal" href="#random.getstate" title="random.getstate"><code>getstate()</code></a>, and <a class="reference internal" href="#random.setstate" title="random.setstate"><code>setstate()</code></a> restores the internal state of the generator to what it was at the time <a class="reference internal" href="#random.getstate" title="random.getstate"><code>getstate()</code></a> was called.</p> </dd>
+</dl> </section> <section id="functions-for-bytes"> <h2>Functions for bytes</h2> <dl class="py function"> <dt class="sig sig-object py" id="random.randbytes">
+<code>random.randbytes(n)</code> </dt> <dd>
+<p>Generate <em>n</em> random bytes.</p> <p>This method should not be used for generating security tokens. Use <a class="reference internal" href="secrets#secrets.token_bytes" title="secrets.token_bytes"><code>secrets.token_bytes()</code></a> instead.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </dd>
+</dl> </section> <section id="functions-for-integers"> <h2>Functions for integers</h2> <dl class="py function"> <dt class="sig sig-object py" id="random.randrange">
+<code>random.randrange(stop)</code> </dt> <dt class="sig sig-object py"> <span class="sig-prename descclassname">random.</span><span class="sig-name descname">randrange</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">start</span></em>, <em class="sig-param"><span class="n">stop</span></em><span class="optional">[</span>, <em class="sig-param"><span class="n">step</span></em><span class="optional">]</span><span class="sig-paren">)</span>
+</dt> <dd>
+<p>Return a randomly selected element from <code>range(start, stop, step)</code>.</p> <p>This is roughly equivalent to <code>choice(range(start, stop, step))</code> but supports arbitrarily large ranges and is optimized for common cases.</p> <p>The positional argument pattern matches the <a class="reference internal" href="stdtypes#range" title="range"><code>range()</code></a> function.</p> <p>Keyword arguments should not be used because they can be interpreted in unexpected ways. For example <code>randrange(start=100)</code> is interpreted as <code>randrange(0, 100, 1)</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span><a class="reference internal" href="#random.randrange" title="random.randrange"><code>randrange()</code></a> is more sophisticated about producing equally distributed values. Formerly it used a style like <code>int(random()*n)</code> which could produce slightly uneven distributions.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Automatic conversion of non-integer types is no longer supported. Calls such as <code>randrange(10.0)</code> and <code>randrange(Fraction(10, 1))</code> now raise a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.randint">
+<code>random.randint(a, b)</code> </dt> <dd>
+<p>Return a random integer <em>N</em> such that <code>a &lt;= N &lt;= b</code>. Alias for <code>randrange(a, b+1)</code>.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.getrandbits">
+<code>random.getrandbits(k)</code> </dt> <dd>
+<p>Returns a non-negative Python integer with <em>k</em> random bits. This method is supplied with the Mersenne Twister generator and some other generators may also provide it as an optional part of the API. When available, <a class="reference internal" href="#random.getrandbits" title="random.getrandbits"><code>getrandbits()</code></a> enables <a class="reference internal" href="#random.randrange" title="random.randrange"><code>randrange()</code></a> to handle arbitrarily large ranges.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>This method now accepts zero for <em>k</em>.</p> </div> </dd>
+</dl> </section> <section id="functions-for-sequences"> <h2>Functions for sequences</h2> <dl class="py function"> <dt class="sig sig-object py" id="random.choice">
+<code>random.choice(seq)</code> </dt> <dd>
+<p>Return a random element from the non-empty sequence <em>seq</em>. If <em>seq</em> is empty, raises <a class="reference internal" href="exceptions#IndexError" title="IndexError"><code>IndexError</code></a>.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.choices">
+<code>random.choices(population, weights=None, *, cum_weights=None, k=1)</code> </dt> <dd>
+<p>Return a <em>k</em> sized list of elements chosen from the <em>population</em> with replacement. If the <em>population</em> is empty, raises <a class="reference internal" href="exceptions#IndexError" title="IndexError"><code>IndexError</code></a>.</p> <p>If a <em>weights</em> sequence is specified, selections are made according to the relative weights. Alternatively, if a <em>cum_weights</em> sequence is given, the selections are made according to the cumulative weights (perhaps computed using <a class="reference internal" href="itertools#itertools.accumulate" title="itertools.accumulate"><code>itertools.accumulate()</code></a>). For example, the relative weights <code>[10, 5, 30, 5]</code> are equivalent to the cumulative weights <code>[10, 15, 45, 50]</code>. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.</p> <p>If neither <em>weights</em> nor <em>cum_weights</em> are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the <em>population</em> sequence. It is a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> to specify both <em>weights</em> and <em>cum_weights</em>.</p> <p>The <em>weights</em> or <em>cum_weights</em> can use any numeric type that interoperates with the <a class="reference internal" href="functions#float" title="float"><code>float</code></a> values returned by <a class="reference internal" href="#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code>random()</code></a> (that includes integers, floats, and fractions but excludes decimals). Weights are assumed to be non-negative and finite. A <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised if all weights are zero.</p> <p>For a given seed, the <a class="reference internal" href="#random.choices" title="random.choices"><code>choices()</code></a> function with equal weighting typically produces a different sequence than repeated calls to <a class="reference internal" href="#random.choice" title="random.choice"><code>choice()</code></a>. The algorithm used by <a class="reference internal" href="#random.choices" title="random.choices"><code>choices()</code></a> uses floating point arithmetic for internal consistency and speed. The algorithm used by <a class="reference internal" href="#random.choice" title="random.choice"><code>choice()</code></a> defaults to integer arithmetic with repeated selections to avoid small biases from round-off error.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Raises a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if all weights are zero.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.shuffle">
+<code>random.shuffle(x)</code> </dt> <dd>
+<p>Shuffle the sequence <em>x</em> in place.</p> <p>To shuffle an immutable sequence and return a new shuffled list, use <code>sample(x, k=len(x))</code> instead.</p> <p>Note that even for small <code>len(x)</code>, the total number of permutations of <em>x</em> can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Removed the optional parameter <em>random</em>.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.sample">
+<code>random.sample(population, k, *, counts=None)</code> </dt> <dd>
+<p>Return a <em>k</em> length list of unique elements chosen from the population sequence. Used for random sampling without replacement.</p> <p>Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).</p> <p>Members of the population need not be <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a> or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.</p> <p>Repeated elements can be specified one at a time or with the optional keyword-only <em>counts</em> parameter. For example, <code>sample(['red', 'blue'],
+counts=[4, 2], k=5)</code> is equivalent to <code>sample(['red', 'red', 'red', 'red',
+'blue', 'blue'], k=5)</code>.</p> <p>To choose a sample from a range of integers, use a <a class="reference internal" href="stdtypes#range" title="range"><code>range()</code></a> object as an argument. This is especially fast and space efficient for sampling from a large population: <code>sample(range(10000000), k=60)</code>.</p> <p>If the sample size is larger than the population size, a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added the <em>counts</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The <em>population</em> must be a sequence. Automatic conversion of sets to lists is no longer supported.</p> </div> </dd>
+</dl> </section> <section id="discrete-distributions"> <h2>Discrete distributions</h2> <p>The following function generates a discrete distribution.</p> <dl class="py function"> <dt class="sig sig-object py" id="random.binomialvariate">
+<code>random.binomialvariate(n=1, p=0.5)</code> </dt> <dd>
+<p><a class="reference external" href="https://mathworld.wolfram.com/BinomialDistribution.html">Binomial distribution</a>. Return the number of successes for <em>n</em> independent trials with the probability of success in each trial being <em>p</em>:</p> <p>Mathematically equivalent to:</p> <pre data-language="python">sum(random() &lt; p for i in range(n))
+</pre> <p>The number of trials <em>n</em> should be a non-negative integer. The probability of success <em>p</em> should be between <code>0.0 &lt;= p &lt;= 1.0</code>. The result is an integer in the range <code>0 &lt;= X &lt;= n</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
+</dl> </section> <section id="real-valued-distributions"> <span id="id1"></span><h2>Real-valued distributions</h2> <p>The following functions generate specific real-valued distributions. Function parameters are named after the corresponding variables in the distribution’s equation, as used in common mathematical practice; most of these equations can be found in any statistics text.</p> <dl class="py function"> <dt class="sig sig-object py" id="random.random">
+<code>random.random()</code> </dt> <dd>
+<p>Return the next random floating point number in the range <code>0.0 &lt;= X &lt; 1.0</code></p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.uniform">
+<code>random.uniform(a, b)</code> </dt> <dd>
+<p>Return a random floating point number <em>N</em> such that <code>a &lt;= N &lt;= b</code> for <code>a &lt;= b</code> and <code>b &lt;= N &lt;= a</code> for <code>b &lt; a</code>.</p> <p>The end-point value <code>b</code> may or may not be included in the range depending on floating-point rounding in the equation <code>a + (b-a) * random()</code>.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.triangular">
+<code>random.triangular(low, high, mode)</code> </dt> <dd>
+<p>Return a random floating point number <em>N</em> such that <code>low &lt;= N &lt;= high</code> and with the specified <em>mode</em> between those bounds. The <em>low</em> and <em>high</em> bounds default to zero and one. The <em>mode</em> argument defaults to the midpoint between the bounds, giving a symmetric distribution.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.betavariate">
+<code>random.betavariate(alpha, beta)</code> </dt> <dd>
+<p>Beta distribution. Conditions on the parameters are <code>alpha &gt; 0</code> and <code>beta &gt; 0</code>. Returned values range between 0 and 1.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.expovariate">
+<code>random.expovariate(lambd=1.0)</code> </dt> <dd>
+<p>Exponential distribution. <em>lambd</em> is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called “lambda”, but that is a reserved word in Python.) Returned values range from 0 to positive infinity if <em>lambd</em> is positive, and from negative infinity to 0 if <em>lambd</em> is negative.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added the default value for <code>lambd</code>.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.gammavariate">
+<code>random.gammavariate(alpha, beta)</code> </dt> <dd>
+<p>Gamma distribution. (<em>Not</em> the gamma function!) The shape and scale parameters, <em>alpha</em> and <em>beta</em>, must have positive values. (Calling conventions vary and some sources define ‘beta’ as the inverse of the scale).</p> <p>The probability distribution function is:</p> <pre data-language="python"> x ** (alpha - 1) * math.exp(-x / beta)
+pdf(x) = --------------------------------------
+ math.gamma(alpha) * beta ** alpha
+</pre> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.gauss">
+<code>random.gauss(mu=0.0, sigma=1.0)</code> </dt> <dd>
+<p>Normal distribution, also called the Gaussian distribution. <em>mu</em> is the mean, and <em>sigma</em> is the standard deviation. This is slightly faster than the <a class="reference internal" href="#random.normalvariate" title="random.normalvariate"><code>normalvariate()</code></a> function defined below.</p> <p>Multithreading note: When two threads call this function simultaneously, it is possible that they will receive the same return value. This can be avoided in three ways. 1) Have each thread use a different instance of the random number generator. 2) Put locks around all calls. 3) Use the slower, but thread-safe <a class="reference internal" href="#random.normalvariate" title="random.normalvariate"><code>normalvariate()</code></a> function instead.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><em>mu</em> and <em>sigma</em> now have default arguments.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.lognormvariate">
+<code>random.lognormvariate(mu, sigma)</code> </dt> <dd>
+<p>Log normal distribution. If you take the natural logarithm of this distribution, you’ll get a normal distribution with mean <em>mu</em> and standard deviation <em>sigma</em>. <em>mu</em> can have any value, and <em>sigma</em> must be greater than zero.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.normalvariate">
+<code>random.normalvariate(mu=0.0, sigma=1.0)</code> </dt> <dd>
+<p>Normal distribution. <em>mu</em> is the mean, and <em>sigma</em> is the standard deviation.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><em>mu</em> and <em>sigma</em> now have default arguments.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.vonmisesvariate">
+<code>random.vonmisesvariate(mu, kappa)</code> </dt> <dd>
+<p><em>mu</em> is the mean angle, expressed in radians between 0 and 2*<em>pi</em>, and <em>kappa</em> is the concentration parameter, which must be greater than or equal to zero. If <em>kappa</em> is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*<em>pi</em>.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.paretovariate">
+<code>random.paretovariate(alpha)</code> </dt> <dd>
+<p>Pareto distribution. <em>alpha</em> is the shape parameter.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="random.weibullvariate">
+<code>random.weibullvariate(alpha, beta)</code> </dt> <dd>
+<p>Weibull distribution. <em>alpha</em> is the scale parameter and <em>beta</em> is the shape parameter.</p> </dd>
+</dl> </section> <section id="alternative-generator"> <h2>Alternative Generator</h2> <dl class="py class"> <dt class="sig sig-object py" id="random.Random">
+<code>class random.Random([seed])</code> </dt> <dd>
+<p>Class that implements the default pseudo-random number generator used by the <a class="reference internal" href="#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code>random</code></a> module.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Formerly the <em>seed</em> could be any hashable object. Now it is limited to: <code>None</code>, <a class="reference internal" href="functions#int" title="int"><code>int</code></a>, <a class="reference internal" href="functions#float" title="float"><code>float</code></a>, <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>, or <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>.</p> </div> <p>Subclasses of <code>Random</code> should override the following methods if they wish to make use of a different basic generator:</p> <dl class="py method"> <dt class="sig sig-object py" id="random.Random.seed">
+<code>seed(a=None, version=2)</code> </dt> <dd>
+<p>Override this method in subclasses to customise the <a class="reference internal" href="#random.seed" title="random.seed"><code>seed()</code></a> behaviour of <code>Random</code> instances.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="random.Random.getstate">
+<code>getstate()</code> </dt> <dd>
+<p>Override this method in subclasses to customise the <a class="reference internal" href="#random.getstate" title="random.getstate"><code>getstate()</code></a> behaviour of <code>Random</code> instances.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="random.Random.setstate">
+<code>setstate(state)</code> </dt> <dd>
+<p>Override this method in subclasses to customise the <a class="reference internal" href="#random.setstate" title="random.setstate"><code>setstate()</code></a> behaviour of <code>Random</code> instances.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="random.Random.random">
+<code>random()</code> </dt> <dd>
+<p>Override this method in subclasses to customise the <a class="reference internal" href="#random.random" title="random.random"><code>random()</code></a> behaviour of <code>Random</code> instances.</p> </dd>
+</dl> <p>Optionally, a custom generator subclass can also supply the following method:</p> <dl class="py method"> <dt class="sig sig-object py" id="random.Random.getrandbits">
+<code>getrandbits(k)</code> </dt> <dd>
+<p>Override this method in subclasses to customise the <a class="reference internal" href="#random.getrandbits" title="random.getrandbits"><code>getrandbits()</code></a> behaviour of <code>Random</code> instances.</p> </dd>
+</dl> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="random.SystemRandom">
+<code>class random.SystemRandom([seed])</code> </dt> <dd>
+<p>Class that uses the <a class="reference internal" href="os#os.urandom" title="os.urandom"><code>os.urandom()</code></a> function for generating random numbers from sources provided by the operating system. Not available on all systems. Does not rely on software state, and sequences are not reproducible. Accordingly, the <a class="reference internal" href="#random.seed" title="random.seed"><code>seed()</code></a> method has no effect and is ignored. The <a class="reference internal" href="#random.getstate" title="random.getstate"><code>getstate()</code></a> and <a class="reference internal" href="#random.setstate" title="random.setstate"><code>setstate()</code></a> methods raise <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a> if called.</p> </dd>
+</dl> </section> <section id="notes-on-reproducibility"> <h2>Notes on Reproducibility</h2> <p>Sometimes it is useful to be able to reproduce the sequences given by a pseudo-random number generator. By reusing a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running.</p> <p>Most of the random module’s algorithms and seeding functions are subject to change across Python versions, but two aspects are guaranteed not to change:</p> <ul class="simple"> <li>If a new seeding method is added, then a backward compatible seeder will be offered.</li> <li>The generator’s <a class="reference internal" href="#random.Random.random" title="random.Random.random"><code>random()</code></a> method will continue to produce the same sequence when the compatible seeder is given the same seed.</li> </ul> </section> <section id="examples"> <span id="random-examples"></span><h2>Examples</h2> <p>Basic examples:</p> <pre data-language="python">&gt;&gt;&gt; random() # Random float: 0.0 &lt;= x &lt; 1.0
+0.37444887175646646
+
+&gt;&gt;&gt; uniform(2.5, 10.0) # Random float: 2.5 &lt;= x &lt;= 10.0
+3.1800146073117523
+
+&gt;&gt;&gt; expovariate(1 / 5) # Interval between arrivals averaging 5 seconds
+5.148957571865031
+
+&gt;&gt;&gt; randrange(10) # Integer from 0 to 9 inclusive
+7
+
+&gt;&gt;&gt; randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
+26
+
+&gt;&gt;&gt; choice(['win', 'lose', 'draw']) # Single random element from a sequence
+'draw'
+
+&gt;&gt;&gt; deck = 'ace two three four'.split()
+&gt;&gt;&gt; shuffle(deck) # Shuffle a list
+&gt;&gt;&gt; deck
+['four', 'two', 'ace', 'three']
+
+&gt;&gt;&gt; sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement
+[40, 10, 50, 30]
+</pre> <p>Simulations:</p> <pre data-language="python">&gt;&gt;&gt; # Six roulette wheel spins (weighted sampling with replacement)
+&gt;&gt;&gt; choices(['red', 'black', 'green'], [18, 18, 2], k=6)
+['red', 'green', 'black', 'black', 'red', 'black']
+
+&gt;&gt;&gt; # Deal 20 cards without replacement from a deck
+&gt;&gt;&gt; # of 52 playing cards, and determine the proportion of cards
+&gt;&gt;&gt; # with a ten-value: ten, jack, queen, or king.
+&gt;&gt;&gt; deal = sample(['tens', 'low cards'], counts=[16, 36], k=20)
+&gt;&gt;&gt; deal.count('tens') / 20
+0.15
+
+&gt;&gt;&gt; # Estimate the probability of getting 5 or more heads from 7 spins
+&gt;&gt;&gt; # of a biased coin that settles on heads 60% of the time.
+&gt;&gt;&gt; sum(binomialvariate(n=7, p=0.6) &gt;= 5 for i in range(10_000)) / 10_000
+0.4169
+
+&gt;&gt;&gt; # Probability of the median of 5 samples being in middle two quartiles
+&gt;&gt;&gt; def trial():
+... return 2_500 &lt;= sorted(choices(range(10_000), k=5))[2] &lt; 7_500
+...
+&gt;&gt;&gt; sum(trial() for i in range(10_000)) / 10_000
+0.7958
+</pre> <p>Example of <a class="reference external" href="https://en.wikipedia.org/wiki/Bootstrapping_(statistics)">statistical bootstrapping</a> using resampling with replacement to estimate a confidence interval for the mean of a sample:</p> <pre data-language="python"># https://www.thoughtco.com/example-of-bootstrapping-3126155
+from statistics import fmean as mean
+from random import choices
+
+data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
+means = sorted(mean(choices(data, k=len(data))) for i in range(100))
+print(f'The sample mean of {mean(data):.1f} has a 90% confidence '
+ f'interval from {means[5]:.1f} to {means[94]:.1f}')
+</pre> <p>Example of a <a class="reference external" href="https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests">resampling permutation test</a> to determine the statistical significance or <a class="reference external" href="https://en.wikipedia.org/wiki/P-value">p-value</a> of an observed difference between the effects of a drug versus a placebo:</p> <pre data-language="python"># Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
+from statistics import fmean as mean
+from random import shuffle
+
+drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
+placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
+observed_diff = mean(drug) - mean(placebo)
+
+n = 10_000
+count = 0
+combined = drug + placebo
+for i in range(n):
+ shuffle(combined)
+ new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
+ count += (new_diff &gt;= observed_diff)
+
+print(f'{n} label reshufflings produced only {count} instances with a difference')
+print(f'at least as extreme as the observed difference of {observed_diff:.1f}.')
+print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null')
+print(f'hypothesis that there is no difference between the drug and the placebo.')
+</pre> <p>Simulation of arrival times and service deliveries for a multiserver queue:</p> <pre data-language="python">from heapq import heapify, heapreplace
+from random import expovariate, gauss
+from statistics import mean, quantiles
+
+average_arrival_interval = 5.6
+average_service_time = 15.0
+stdev_service_time = 3.5
+num_servers = 3
+
+waits = []
+arrival_time = 0.0
+servers = [0.0] * num_servers # time when each server becomes available
+heapify(servers)
+for i in range(1_000_000):
+ arrival_time += expovariate(1.0 / average_arrival_interval)
+ next_server_available = servers[0]
+ wait = max(0.0, next_server_available - arrival_time)
+ waits.append(wait)
+ service_duration = max(0.0, gauss(average_service_time, stdev_service_time))
+ service_completed = arrival_time + wait + service_duration
+ heapreplace(servers, service_completed)
+
+print(f'Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}')
+print('Quartiles:', [round(q, 1) for q in quantiles(waits)])
+</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference external" href="https://www.youtube.com/watch?v=Iq9DzN6mvYA">Statistics for Hackers</a> a video tutorial by <a class="reference external" href="https://us.pycon.org/2016/speaker/profile/295/">Jake Vanderplas</a> on statistical analysis using just a few fundamental concepts including simulation, sampling, shuffling, and cross-validation.</p> <p><a class="reference external" href="https://nbviewer.org/url/norvig.com/ipython/Economics.ipynb">Economics Simulation</a> a simulation of a marketplace by <a class="reference external" href="https://norvig.com/bio.html">Peter Norvig</a> that shows effective use of many of the tools and distributions provided by this module (gauss, uniform, sample, betavariate, choice, triangular, and randrange).</p> <p><a class="reference external" href="https://nbviewer.org/url/norvig.com/ipython/Probability.ipynb">A Concrete Introduction to Probability (using Python)</a> a tutorial by <a class="reference external" href="https://norvig.com/bio.html">Peter Norvig</a> covering the basics of probability theory, how to write simulations, and how to perform data analysis using Python.</p> </div> </section> <section id="recipes"> <h2>Recipes</h2> <p>These recipes show how to efficiently make random selections from the combinatoric iterators in the <a class="reference internal" href="itertools#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code>itertools</code></a> module:</p> <pre data-language="python">def random_product(*args, repeat=1):
+ "Random selection from itertools.product(*args, **kwds)"
+ pools = [tuple(pool) for pool in args] * repeat
+ return tuple(map(random.choice, pools))
+
+def random_permutation(iterable, r=None):
+ "Random selection from itertools.permutations(iterable, r)"
+ pool = tuple(iterable)
+ r = len(pool) if r is None else r
+ return tuple(random.sample(pool, r))
+
+def random_combination(iterable, r):
+ "Random selection from itertools.combinations(iterable, r)"
+ pool = tuple(iterable)
+ n = len(pool)
+ indices = sorted(random.sample(range(n), r))
+ return tuple(pool[i] for i in indices)
+
+def random_combination_with_replacement(iterable, r):
+ "Choose r elements with replacement. Order the result to match the iterable."
+ # Result will be in set(itertools.combinations_with_replacement(iterable, r)).
+ pool = tuple(iterable)
+ n = len(pool)
+ indices = sorted(random.choices(range(n), k=r))
+ return tuple(pool[i] for i in indices)
+</pre> <p>The default <a class="reference internal" href="#random.random" title="random.random"><code>random()</code></a> returns multiples of 2⁻⁵³ in the range <em>0.0 ≤ x &lt; 1.0</em>. All such numbers are evenly spaced and are exactly representable as Python floats. However, many other representable floats in that interval are not possible selections. For example, <code>0.05954861408025609</code> isn’t an integer multiple of 2⁻⁵³.</p> <p>The following recipe takes a different approach. All floats in the interval are possible selections. The mantissa comes from a uniform distribution of integers in the range <em>2⁵² ≤ mantissa &lt; 2⁵³</em>. The exponent comes from a geometric distribution where exponents smaller than <em>-53</em> occur half as often as the next larger exponent.</p> <pre data-language="python">from random import Random
+from math import ldexp
+
+class FullRandom(Random):
+
+ def random(self):
+ mantissa = 0x10_0000_0000_0000 | self.getrandbits(52)
+ exponent = -53
+ x = 0
+ while not x:
+ x = self.getrandbits(32)
+ exponent += x.bit_length() - 32
+ return ldexp(mantissa, exponent)
+</pre> <p>All <a class="reference internal" href="#real-valued-distributions"><span class="std std-ref">real valued distributions</span></a> in the class will use the new method:</p> <pre data-language="python">&gt;&gt;&gt; fr = FullRandom()
+&gt;&gt;&gt; fr.random()
+0.05954861408025609
+&gt;&gt;&gt; fr.expovariate(0.25)
+8.87925541791544
+</pre> <p>The recipe is conceptually equivalent to an algorithm that chooses from all the multiples of 2⁻¹⁰⁷⁴ in the range <em>0.0 ≤ x &lt; 1.0</em>. All such numbers are evenly spaced, but most have to be rounded down to the nearest representable Python float. (The value 2⁻¹⁰⁷⁴ is the smallest positive unnormalized float and is equal to <code>math.ulp(0.0)</code>.)</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference external" href="https://allendowney.com/research/rand/downey07randfloat.pdf">Generating Pseudo-random Floating-Point Values</a> a paper by Allen B. Downey describing ways to generate more fine-grained floats than normally generated by <a class="reference internal" href="#random.random" title="random.random"><code>random()</code></a>.</p> </div> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/random.html" class="_attribution-link">https://docs.python.org/3.12/library/random.html</a>
+ </p>
+</div>