cpython/Doc/library/random.rst

789 lines
28 KiB
ReStructuredText
Raw Normal View History

:mod:`!random` --- Generate pseudo-random numbers
=================================================
2007-08-15 11:28:22 -03:00
.. module:: random
:synopsis: Generate pseudo-random numbers with various common distributions.
**Source code:** :source:`Lib/random.py`
2007-08-15 11:28:22 -03:00
2011-01-10 15:54:11 -04:00
--------------
2007-08-15 11:28:22 -03:00
This module implements pseudo-random number generators for various
distributions.
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.
2007-08-15 11:28:22 -03:00
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.
Almost all module functions depend on the basic function :func:`.random`, which
generates a random float uniformly in the half-open range ``0.0 <= X < 1.0``.
Python uses the Mersenne Twister as the core generator. It produces 53-bit precision
2007-08-15 11:28:22 -03:00
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.
The functions supplied by this module are actually bound methods of a hidden
instance of the :class:`random.Random` class. You can instantiate your own
instances of :class:`Random` to get generators that don't share state.
2007-08-15 11:28:22 -03:00
Class :class:`Random` 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.
2007-08-15 11:28:22 -03:00
Merged revisions 77952,78030,78102,78104,78107,78206,78216,78296-78297,78328,78331-78332,78336,78339,78343,78378-78379,78415,78559,78717,78791 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r77952 | mark.dickinson | 2010-02-03 10:50:14 -0600 (Wed, 03 Feb 2010) | 1 line Fix test_inspect.py data to match recent change to inspect_fodder.py (r77942). ........ r78030 | benjamin.peterson | 2010-02-06 14:14:10 -0600 (Sat, 06 Feb 2010) | 1 line check type_getattro for correctness in a descriptor corner case ........ r78102 | andrew.kuchling | 2010-02-07 19:35:35 -0600 (Sun, 07 Feb 2010) | 1 line Move distutils into its own subsection; add various items ........ r78104 | andrew.kuchling | 2010-02-08 07:22:24 -0600 (Mon, 08 Feb 2010) | 1 line Add two items; move a subsection ........ r78107 | antoine.pitrou | 2010-02-08 14:25:47 -0600 (Mon, 08 Feb 2010) | 3 lines Clarify and correct description for ccbench and iobench. ........ r78206 | r.david.murray | 2010-02-16 11:55:26 -0600 (Tue, 16 Feb 2010) | 3 lines Make the references to Popen in the description of Call and check_call into links. ........ r78216 | andrew.kuchling | 2010-02-18 08:16:48 -0600 (Thu, 18 Feb 2010) | 1 line Add various items ........ r78296 | andrew.kuchling | 2010-02-21 20:08:45 -0600 (Sun, 21 Feb 2010) | 1 line Re-word ........ r78297 | andrew.kuchling | 2010-02-21 20:29:10 -0600 (Sun, 21 Feb 2010) | 1 line #7076: mention SystemRandom class near start of the module docs; reword change description for clarity. Noted by Shawn Ligocki. ........ r78328 | jack.diederich | 2010-02-22 12:17:16 -0600 (Mon, 22 Feb 2010) | 1 line fixes issue #7530, serve_forever() ........ r78331 | andrew.kuchling | 2010-02-22 12:38:23 -0600 (Mon, 22 Feb 2010) | 1 line Fix comment typo ........ r78332 | andrew.kuchling | 2010-02-22 12:42:07 -0600 (Mon, 22 Feb 2010) | 2 lines #7627: MH.remove() would fail if the MH mailbox was locked; it would call _unlock_file() and pass it a closed file object. Noted by Rob Austein. ........ r78336 | jack.diederich | 2010-02-22 13:55:22 -0600 (Mon, 22 Feb 2010) | 1 line fixes issue #1522237, bad init check in _threading_local ........ r78339 | jack.diederich | 2010-02-22 15:27:38 -0600 (Mon, 22 Feb 2010) | 1 line * fix issue#7476 ........ r78343 | andrew.kuchling | 2010-02-22 16:48:41 -0600 (Mon, 22 Feb 2010) | 10 lines #2560: remove an unnecessary 'for' loop from my_fgets() in Parser/myreadline.c. Noted by Joseph Armbruster; patch by Jessica McKellar. The original code was 'for (;;) {...}', where ... ended with a 'return -2' statement and did not contain a 'break' or 'continue' statement. Therefore, the body of the loop is always executed once. Once upon a time there was a 'continue' in the loop, but it was removed in rev36346, committed by mwh on Wed Jul 7 17:44:12 2004. ........ r78378 | jack.diederich | 2010-02-23 11:23:30 -0600 (Tue, 23 Feb 2010) | 1 line fixup markup error ........ r78379 | jack.diederich | 2010-02-23 13:34:06 -0600 (Tue, 23 Feb 2010) | 1 line issue#6442 use in operator instead of has_key ........ r78415 | dirkjan.ochtman | 2010-02-23 22:00:52 -0600 (Tue, 23 Feb 2010) | 1 line Issue #7733: add explicit reference in asyncore docs. ........ r78559 | andrew.kuchling | 2010-03-01 13:45:21 -0600 (Mon, 01 Mar 2010) | 1 line #7637: update discussion of minidom.unlink() and garbage collection ........ r78717 | benjamin.peterson | 2010-03-05 21:13:33 -0600 (Fri, 05 Mar 2010) | 1 line settscdump is definitely an implementation detail ........ r78791 | andrew.kuchling | 2010-03-08 06:00:39 -0600 (Mon, 08 Mar 2010) | 1 line Add various items ........
2010-03-21 19:03:03 -03:00
The :mod:`random` module also provides the :class:`SystemRandom` class which
uses the system function :func:`os.urandom` to generate random numbers
from sources provided by the operating system.
2007-08-15 11:28:22 -03:00
.. warning::
The pseudo-random generators of this module should not be used for
2016-04-16 12:42:33 -03:00
security purposes. For security or cryptographic uses, see the
:mod:`secrets` module.
.. seealso::
2007-08-15 11:28:22 -03:00
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
<https://code.activestate.com/recipes/576707-long-period-random-number-generator/>`_ for a compatible alternative
random number generator with a long period and comparatively simple update
operations.
.. note::
The global random number generator and instances of :class:`Random` are thread-safe.
However, in the free-threaded build, concurrent calls to the global generator or
to the same instance of :class:`Random` may encounter contention and poor performance.
Consider using separate instances of :class:`Random` per thread instead.
Bookkeeping functions
---------------------
2007-08-15 11:28:22 -03:00
.. function:: seed(a=None, version=2)
2007-08-15 11:28:22 -03:00
Initialize the random number generator.
2007-08-15 11:28:22 -03:00
If *a* is omitted or ``None``, 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 :func:`os.urandom` function for details
on availability).
2007-08-15 11:28:22 -03:00
If *a* is an int, it is used directly.
With version 2 (the default), a :class:`str`, :class:`bytes`, or :class:`bytearray`
2016-09-04 15:17:28 -03:00
object gets converted to an :class:`int` and all of its bits are used.
With version 1 (provided for reproducing random sequences from older versions
of Python), the algorithm for :class:`str` and :class:`bytes` generates a
narrower range of seeds.
.. versionchanged:: 3.2
Moved to the version 2 scheme which uses all of the bits in a string seed.
2007-08-15 11:28:22 -03:00
.. versionchanged:: 3.11
The *seed* must be one of the following types:
``None``, :class:`int`, :class:`float`, :class:`str`,
:class:`bytes`, or :class:`bytearray`.
2007-08-15 11:28:22 -03:00
.. function:: getstate()
Return an object capturing the current internal state of the generator. This
object can be passed to :func:`setstate` to restore the state.
.. function:: setstate(state)
*state* should have been obtained from a previous call to :func:`getstate`, and
:func:`setstate` restores the internal state of the generator to what it was at
the time :func:`getstate` was called.
2007-08-15 11:28:22 -03:00
Functions for bytes
-------------------
2007-08-15 11:28:22 -03:00
.. function:: randbytes(n)
Generate *n* random bytes.
This method should not be used for generating security tokens.
Use :func:`secrets.token_bytes` instead.
.. versionadded:: 3.9
Functions for integers
----------------------
2007-08-15 11:28:22 -03:00
.. function:: randrange(stop)
randrange(start, stop[, step])
2007-08-15 11:28:22 -03:00
Return a randomly selected element from ``range(start, stop, step)``.
2007-08-15 11:28:22 -03:00
This is roughly equivalent to ``choice(range(start, stop, step))`` but
supports arbitrarily large ranges and is optimized for common cases.
The positional argument pattern matches the :func:`range` function.
Keyword arguments should not be used because they can be interpreted
in unexpected ways. For example ``randrange(start=100)`` is interpreted
as ``randrange(0, 100, 1)``.
.. versionchanged:: 3.2
:meth:`randrange` is more sophisticated about producing equally distributed
values. Formerly it used a style like ``int(random()*n)`` which could produce
slightly uneven distributions.
2007-08-15 11:28:22 -03:00
.. versionchanged:: 3.12
Automatic conversion of non-integer types is no longer supported.
Calls such as ``randrange(10.0)`` and ``randrange(Fraction(10, 1))``
now raise a :exc:`TypeError`.
2007-08-15 11:28:22 -03:00
.. function:: randint(a, b)
Return a random integer *N* such that ``a <= N <= b``. Alias for
``randrange(a, b+1)``.
2007-08-15 11:28:22 -03:00
.. function:: getrandbits(k)
Returns a non-negative Python integer with *k* 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,
:meth:`getrandbits` enables :meth:`randrange` to handle arbitrarily large
ranges.
.. versionchanged:: 3.9
This method now accepts zero for *k*.
2007-08-15 11:28:22 -03:00
Functions for sequences
-----------------------
2007-08-15 11:28:22 -03:00
.. function:: choice(seq)
Return a random element from the non-empty sequence *seq*. If *seq* is empty,
raises :exc:`IndexError`.
.. function:: 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 :exc:`IndexError`.
If a *weights* sequence is specified, selections 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 :func:`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 to
cumulative weights before making selections, so supplying the cumulative
weights saves work.
If neither *weights* nor *cum_weights* are specified, selections are made
with equal probability. If a weights sequence is supplied, it must be
the same length as the *population* sequence. It is a :exc:`TypeError`
to specify both *weights* and *cum_weights*.
The *weights* or *cum_weights* can use any numeric type that interoperates
with the :class:`float` values returned by :func:`random` (that includes
integers, floats, and fractions but excludes decimals). Weights are assumed
to be non-negative and finite. A :exc:`ValueError` is raised if all
weights are zero.
2007-08-15 11:28:22 -03:00
For a given seed, the :func:`choices` function with equal weighting
typically produces a different sequence than repeated calls to
:func:`choice`. The algorithm used by :func:`choices` uses floating-point
arithmetic for internal consistency and speed. The algorithm used
by :func:`choice` defaults to integer arithmetic with repeated selections
to avoid small biases from round-off error.
.. versionadded:: 3.6
.. versionchanged:: 3.9
Raises a :exc:`ValueError` if all weights are zero.
.. function:: shuffle(x)
2007-08-15 11:28:22 -03:00
Shuffle the sequence *x* in place.
2007-08-15 11:28:22 -03:00
To shuffle an immutable sequence and return a new shuffled list, use
``sample(x, k=len(x))`` instead.
Note that even for small ``len(x)``, the total number of permutations of *x*
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.
2007-08-15 11:28:22 -03:00
.. versionchanged:: 3.11
Removed the optional parameter *random*.
2007-08-15 11:28:22 -03:00
.. function:: sample(population, k, *, counts=None)
2007-08-15 11:28:22 -03:00
Return a *k* length list of unique elements chosen from the population
sequence. Used for random sampling without replacement.
2007-08-15 11:28:22 -03:00
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).
Merged revisions 58742-58816 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r58745 | georg.brandl | 2007-11-01 10:19:33 -0700 (Thu, 01 Nov 2007) | 2 lines #1364: os.lstat is available on Windows too, as an alias to os.stat. ........ r58750 | christian.heimes | 2007-11-01 12:48:10 -0700 (Thu, 01 Nov 2007) | 1 line Backport of import tests for bug http://bugs.python.org/issue1293 and bug http://bugs.python.org/issue1342 ........ r58751 | christian.heimes | 2007-11-01 13:11:06 -0700 (Thu, 01 Nov 2007) | 1 line Removed non ASCII text from test as requested by Guido. Sorry :/ ........ r58753 | georg.brandl | 2007-11-01 13:37:02 -0700 (Thu, 01 Nov 2007) | 2 lines Fix markup glitch. ........ r58757 | gregory.p.smith | 2007-11-01 14:08:14 -0700 (Thu, 01 Nov 2007) | 4 lines Fix bug introduced in revision 58385. Database keys could no longer have NULL bytes in them. Replace the errant strdup with a malloc+memcpy. Adds a unit test for the correct behavior. ........ r58758 | gregory.p.smith | 2007-11-01 14:15:36 -0700 (Thu, 01 Nov 2007) | 3 lines Undo revision 58533 58534 fixes. Those were a workaround for a problem introduced by 58385. ........ r58759 | gregory.p.smith | 2007-11-01 14:17:47 -0700 (Thu, 01 Nov 2007) | 2 lines false "fix" undone as correct problem was found and fixed. ........ r58765 | mark.summerfield | 2007-11-02 01:24:59 -0700 (Fri, 02 Nov 2007) | 3 lines Added more file-handling related cross-references. ........ r58766 | nick.coghlan | 2007-11-02 03:09:12 -0700 (Fri, 02 Nov 2007) | 1 line Fix for bug 1705170 - contextmanager swallowing StopIteration (2.5 backport candidate) ........ r58784 | thomas.heller | 2007-11-02 12:10:24 -0700 (Fri, 02 Nov 2007) | 4 lines Issue #1292: On alpha, arm, ppc, and s390 linux systems the --with-system-ffi configure option defaults to "yes" because the bundled libffi sources are too old. ........ r58785 | thomas.heller | 2007-11-02 12:11:23 -0700 (Fri, 02 Nov 2007) | 1 line Enable the full ctypes c_longdouble tests again. ........ r58796 | georg.brandl | 2007-11-02 13:06:17 -0700 (Fri, 02 Nov 2007) | 4 lines Make "hashable" a glossary entry and clarify docs on __cmp__, __eq__ and __hash__. I hope the concept of hashability is better understandable now. Thanks to Tim Hatch for pointing out the flaws here. ........
2007-11-02 20:46:40 -03:00
Members of the population need not be :term:`hashable` or unique. If the population
2007-08-15 11:28:22 -03:00
contains repeats, then each occurrence is a possible selection in the sample.
Repeated elements can be specified one at a time or with the optional
keyword-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 :func:`range` object as an
2007-08-15 11:28:22 -03:00
argument. This is especially fast and space efficient for sampling from a large
population: ``sample(range(10000000), k=60)``.
2007-08-15 11:28:22 -03:00
2012-07-09 16:43:57 -03:00
If the sample size is larger than the population size, a :exc:`ValueError`
is raised.
.. versionchanged:: 3.9
Added the *counts* parameter.
.. versionchanged:: 3.11
The *population* must be a sequence. Automatic conversion of sets
to lists is no longer supported.
Discrete distributions
----------------------
The following function generates a discrete distribution.
.. function:: binomialvariate(n=1, p=0.5)
`Binomial distribution
<https://mathworld.wolfram.com/BinomialDistribution.html>`_.
Return the number of successes for *n* independent trials with the
probability of success in each trial being *p*:
Mathematically equivalent to::
sum(random() < p for i in range(n))
The number of trials *n* should be a non-negative integer.
The probability of success *p* should be between ``0.0 <= p <= 1.0``.
The result is an integer in the range ``0 <= X <= n``.
.. versionadded:: 3.12
2020-10-13 20:41:26 -03:00
.. _real-valued-distributions:
Real-valued distributions
-------------------------
2007-08-15 11:28:22 -03:00
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.
.. function:: random()
Return the next random floating-point number in the range ``0.0 <= X < 1.0``
2007-08-15 11:28:22 -03:00
.. function:: uniform(a, b)
Return a random floating-point number *N* such that ``a <= N <= b`` for
Merged revisions 68633,68648,68667,68706,68718,68720-68721,68724-68727,68739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r68633 | thomas.heller | 2009-01-16 12:53:44 -0600 (Fri, 16 Jan 2009) | 3 lines Change an example in the docs to avoid a mistake when the code is copy pasted and changed afterwards. ........ r68648 | benjamin.peterson | 2009-01-16 22:28:57 -0600 (Fri, 16 Jan 2009) | 1 line use enumerate ........ r68667 | amaury.forgeotdarc | 2009-01-17 14:18:59 -0600 (Sat, 17 Jan 2009) | 3 lines #4077: No need to append \n when calling Py_FatalError + fix a declaration to make it match the one in pythonrun.h ........ r68706 | benjamin.peterson | 2009-01-17 19:28:46 -0600 (Sat, 17 Jan 2009) | 1 line fix grammar ........ r68718 | georg.brandl | 2009-01-18 04:42:35 -0600 (Sun, 18 Jan 2009) | 1 line #4976: union() and intersection() take multiple args, but talk about "the other". ........ r68720 | georg.brandl | 2009-01-18 04:45:22 -0600 (Sun, 18 Jan 2009) | 1 line #4974: fix redundant mention of lists and tuples. ........ r68721 | georg.brandl | 2009-01-18 04:48:16 -0600 (Sun, 18 Jan 2009) | 1 line #4914: trunc is in math. ........ r68724 | georg.brandl | 2009-01-18 07:24:10 -0600 (Sun, 18 Jan 2009) | 1 line #4979: correct result range for some random functions. ........ r68725 | georg.brandl | 2009-01-18 07:47:26 -0600 (Sun, 18 Jan 2009) | 1 line #4857: fix augmented assignment target spec. ........ r68726 | georg.brandl | 2009-01-18 08:41:52 -0600 (Sun, 18 Jan 2009) | 1 line #4923: clarify what was added. ........ r68727 | georg.brandl | 2009-01-18 12:25:30 -0600 (Sun, 18 Jan 2009) | 1 line #4986: augassigns are not expressions. ........ r68739 | benjamin.peterson | 2009-01-18 15:11:38 -0600 (Sun, 18 Jan 2009) | 1 line fix test that wasn't working as expected #4990 ........
2009-01-18 18:27:04 -04:00
``a <= b`` and ``b <= N <= a`` for ``b < a``.
2007-08-15 11:28:22 -03:00
The end-point value ``b`` may or may not be included in the range
depending on floating-point rounding in the expression
``a + (b-a) * random()``.
Merged revisions 61724-61725,61731-61735,61737,61739,61741,61743-61744,61753,61761,61765-61767,61769,61773,61776-61778,61780-61783,61788,61793,61796,61807,61813 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ................ r61724 | martin.v.loewis | 2008-03-22 01:01:12 +0100 (Sat, 22 Mar 2008) | 49 lines Merged revisions 61602-61723 via svnmerge from svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r61626 | david.wolever | 2008-03-19 17:19:16 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Added fixer for implicit local imports. See #2414. ........ r61628 | david.wolever | 2008-03-19 17:57:43 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Added a class for tests which should not run if a particular import is found. ........ r61629 | collin.winter | 2008-03-19 17:58:19 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Two more relative import fixes in pgen2. ........ r61635 | david.wolever | 2008-03-19 20:16:03 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Fixed print fixer so it will do the Right Thing when it encounters __future__.print_function. 2to3 gets upset, though, so the tests have been commented out. ........ r61637 | david.wolever | 2008-03-19 21:37:17 +0100 (Mi, 19 M?\195?\164r 2008) | 3 lines Added a fixer for itertools imports (from itertools import imap, ifilterfalse --> from itertools import filterfalse) ........ r61645 | david.wolever | 2008-03-19 23:22:35 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line SVN is happier when you add the files you create... -_-' ........ r61654 | david.wolever | 2008-03-20 01:09:56 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Added an explicit sort order to fixers -- fixes problems like #2427 ........ r61664 | david.wolever | 2008-03-20 04:32:40 +0100 (Do, 20 M?\195?\164r 2008) | 3 lines Fixes #2428 -- comments are no longer eatten by __future__ fixer. ........ r61673 | david.wolever | 2008-03-20 17:22:40 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Added 2to3 node pretty-printer ........ r61679 | david.wolever | 2008-03-20 20:50:42 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Made node printing a little bit prettier ........ r61723 | martin.v.loewis | 2008-03-22 00:59:27 +0100 (Sa, 22 M?\195?\164r 2008) | 2 lines Fix whitespace. ........ ................ r61725 | martin.v.loewis | 2008-03-22 01:02:41 +0100 (Sat, 22 Mar 2008) | 2 lines Install lib2to3. ................ r61731 | facundo.batista | 2008-03-22 03:45:37 +0100 (Sat, 22 Mar 2008) | 4 lines Small fix that complicated the test actually when that test failed. ................ r61732 | alexandre.vassalotti | 2008-03-22 05:08:44 +0100 (Sat, 22 Mar 2008) | 2 lines Added warning for the removal of 'hotshot' in Py3k. ................ r61733 | georg.brandl | 2008-03-22 11:07:29 +0100 (Sat, 22 Mar 2008) | 4 lines #1918: document that weak references *to* an object are cleared before the object's __del__ is called, to ensure that the weak reference callback (if any) finds the object healthy. ................ r61734 | georg.brandl | 2008-03-22 11:56:23 +0100 (Sat, 22 Mar 2008) | 2 lines Activate the Sphinx doctest extension and convert howto/functional to use it. ................ r61735 | georg.brandl | 2008-03-22 11:58:38 +0100 (Sat, 22 Mar 2008) | 2 lines Allow giving source names on the cmdline. ................ r61737 | georg.brandl | 2008-03-22 12:00:48 +0100 (Sat, 22 Mar 2008) | 2 lines Fixup this HOWTO's doctest blocks so that they can be run with sphinx' doctest builder. ................ r61739 | georg.brandl | 2008-03-22 12:47:10 +0100 (Sat, 22 Mar 2008) | 2 lines Test decimal.rst doctests as far as possible with sphinx doctest. ................ r61741 | georg.brandl | 2008-03-22 13:04:26 +0100 (Sat, 22 Mar 2008) | 2 lines Make doctests in re docs usable with sphinx' doctest. ................ r61743 | georg.brandl | 2008-03-22 13:59:37 +0100 (Sat, 22 Mar 2008) | 2 lines Make more doctests in pprint docs testable. ................ r61744 | georg.brandl | 2008-03-22 14:07:06 +0100 (Sat, 22 Mar 2008) | 2 lines No need to specify explicit "doctest_block" anymore. ................ r61753 | georg.brandl | 2008-03-22 21:08:43 +0100 (Sat, 22 Mar 2008) | 2 lines Fix-up syntax problems. ................ r61761 | georg.brandl | 2008-03-22 22:06:20 +0100 (Sat, 22 Mar 2008) | 4 lines Make collections' doctests executable. (The <BLANKLINE>s will be stripped from presentation output.) ................ r61765 | georg.brandl | 2008-03-22 22:21:57 +0100 (Sat, 22 Mar 2008) | 2 lines Test doctests in datetime docs. ................ r61766 | georg.brandl | 2008-03-22 22:26:44 +0100 (Sat, 22 Mar 2008) | 2 lines Test doctests in operator docs. ................ r61767 | georg.brandl | 2008-03-22 22:38:33 +0100 (Sat, 22 Mar 2008) | 2 lines Enable doctests in functions.rst. Already found two errors :) ................ r61769 | georg.brandl | 2008-03-22 23:04:10 +0100 (Sat, 22 Mar 2008) | 3 lines Enable doctest running for several other documents. We have now over 640 doctests that are run with "make doctest". ................ r61773 | raymond.hettinger | 2008-03-23 01:55:46 +0100 (Sun, 23 Mar 2008) | 1 line Simplify demo code. ................ r61776 | neal.norwitz | 2008-03-23 04:43:33 +0100 (Sun, 23 Mar 2008) | 7 lines Try to make this test a little more robust and not fail with: timeout (10.0025) is more than 2 seconds more than expected (0.001) I'm assuming this problem is caused by DNS lookup. This change does a DNS lookup of the hostname before trying to connect, so the time is not included. ................ r61777 | neal.norwitz | 2008-03-23 05:08:30 +0100 (Sun, 23 Mar 2008) | 1 line Speed up the test by avoiding socket timeouts. ................ r61778 | neal.norwitz | 2008-03-23 05:43:09 +0100 (Sun, 23 Mar 2008) | 1 line Skip the epoll test if epoll() does not work ................ r61780 | neal.norwitz | 2008-03-23 06:47:20 +0100 (Sun, 23 Mar 2008) | 1 line Suppress failure (to avoid a flaky test) if we cannot connect to svn.python.org ................ r61781 | neal.norwitz | 2008-03-23 07:13:25 +0100 (Sun, 23 Mar 2008) | 4 lines Move itertools before future_builtins since the latter depends on the former. From a clean build importing future_builtins would fail since itertools wasn't built yet. ................ r61782 | neal.norwitz | 2008-03-23 07:16:04 +0100 (Sun, 23 Mar 2008) | 1 line Try to prevent the alarm going off early in tearDown ................ r61783 | neal.norwitz | 2008-03-23 07:19:57 +0100 (Sun, 23 Mar 2008) | 4 lines Remove compiler warnings (on Alpha at least) about using chars as array subscripts. Using chars are dangerous b/c they are signed on some platforms and unsigned on others. ................ r61788 | georg.brandl | 2008-03-23 09:05:30 +0100 (Sun, 23 Mar 2008) | 2 lines Make the doctests presentation-friendlier. ................ r61793 | amaury.forgeotdarc | 2008-03-23 10:55:29 +0100 (Sun, 23 Mar 2008) | 4 lines #1477: ur'\U0010FFFF' raised in narrow unicode builds. Corrected the raw-unicode-escape codec to use UTF-16 surrogates in this case, just like the unicode-escape codec. ................ r61796 | raymond.hettinger | 2008-03-23 14:32:32 +0100 (Sun, 23 Mar 2008) | 1 line Issue 1681432: Add triangular distribution the random module. ................ r61807 | raymond.hettinger | 2008-03-23 20:37:53 +0100 (Sun, 23 Mar 2008) | 4 lines Adopt Nick's suggestion for useful default arguments. Clean-up floating point issues by adding true division and float constants. ................ r61813 | gregory.p.smith | 2008-03-23 22:04:43 +0100 (Sun, 23 Mar 2008) | 6 lines Fix gzip to deal with CRC's being signed values in Python 2.x properly and to read 32bit values as unsigned to start with rather than applying signedness fixups allover the place afterwards. This hopefully fixes the test_tarfile failure on the alpha/tru64 buildbot. ................
2008-03-23 18:54:12 -03:00
.. function:: triangular(low, high, mode)
Return a random floating-point number *N* such that ``low <= N <= high`` and
Merged revisions 61834,61841-61842,61851-61853,61863-61864,61869-61870,61874,61889 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r61834 | raymond.hettinger | 2008-03-24 07:07:49 +0100 (Mon, 24 Mar 2008) | 1 line Tighten documentation for Random.triangular. ........ r61841 | raymond.hettinger | 2008-03-24 09:17:39 +0100 (Mon, 24 Mar 2008) | 1 line Issue 2460: Make Ellipsis objects copyable. ........ r61842 | georg.brandl | 2008-03-24 10:34:34 +0100 (Mon, 24 Mar 2008) | 2 lines #1700821: add a note to audioop docs about signedness of sample formats. ........ r61851 | christian.heimes | 2008-03-24 20:57:42 +0100 (Mon, 24 Mar 2008) | 1 line Added quick hack for bzr ........ r61852 | christian.heimes | 2008-03-24 20:58:17 +0100 (Mon, 24 Mar 2008) | 1 line Added quick hack for bzr ........ r61853 | amaury.forgeotdarc | 2008-03-24 22:04:10 +0100 (Mon, 24 Mar 2008) | 4 lines Issue2469: Correct a typo I introduced at r61793: compilation error with UCS4 builds. All buildbots compile with UCS2... ........ r61863 | neal.norwitz | 2008-03-25 05:17:38 +0100 (Tue, 25 Mar 2008) | 2 lines Fix a bunch of UnboundLocalErrors when the tests fail. ........ r61864 | neal.norwitz | 2008-03-25 05:18:18 +0100 (Tue, 25 Mar 2008) | 2 lines Try to fix a bunch of compiler warnings on Win64. ........ r61869 | neal.norwitz | 2008-03-25 07:35:10 +0100 (Tue, 25 Mar 2008) | 3 lines Don't try to close a non-open file. Don't let file removal cause the test to fail. ........ r61870 | neal.norwitz | 2008-03-25 08:00:39 +0100 (Tue, 25 Mar 2008) | 7 lines Try to get this test to be more stable: * disable gc during the test run because we are spawning objects and there was an exception when calling Popen.__del__ * Always set an alarm handler so the process doesn't exit if the test fails (should probably add assertions on the value of hndl_called in more places) * Using a negative time causes Linux to treat it as zero, so disable that test. ........ r61874 | gregory.p.smith | 2008-03-25 08:31:28 +0100 (Tue, 25 Mar 2008) | 2 lines Use a 32-bit unsigned int here, a long is not needed. ........ r61889 | georg.brandl | 2008-03-25 12:59:51 +0100 (Tue, 25 Mar 2008) | 2 lines Move declarations to block start. ........
2008-03-25 11:56:36 -03:00
with the specified *mode* between those bounds. The *low* and *high* bounds
default to zero and one. The *mode* argument defaults to the midpoint
between the bounds, giving a symmetric distribution.
Merged revisions 61724-61725,61731-61735,61737,61739,61741,61743-61744,61753,61761,61765-61767,61769,61773,61776-61778,61780-61783,61788,61793,61796,61807,61813 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ................ r61724 | martin.v.loewis | 2008-03-22 01:01:12 +0100 (Sat, 22 Mar 2008) | 49 lines Merged revisions 61602-61723 via svnmerge from svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r61626 | david.wolever | 2008-03-19 17:19:16 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Added fixer for implicit local imports. See #2414. ........ r61628 | david.wolever | 2008-03-19 17:57:43 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Added a class for tests which should not run if a particular import is found. ........ r61629 | collin.winter | 2008-03-19 17:58:19 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Two more relative import fixes in pgen2. ........ r61635 | david.wolever | 2008-03-19 20:16:03 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line Fixed print fixer so it will do the Right Thing when it encounters __future__.print_function. 2to3 gets upset, though, so the tests have been commented out. ........ r61637 | david.wolever | 2008-03-19 21:37:17 +0100 (Mi, 19 M?\195?\164r 2008) | 3 lines Added a fixer for itertools imports (from itertools import imap, ifilterfalse --> from itertools import filterfalse) ........ r61645 | david.wolever | 2008-03-19 23:22:35 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line SVN is happier when you add the files you create... -_-' ........ r61654 | david.wolever | 2008-03-20 01:09:56 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Added an explicit sort order to fixers -- fixes problems like #2427 ........ r61664 | david.wolever | 2008-03-20 04:32:40 +0100 (Do, 20 M?\195?\164r 2008) | 3 lines Fixes #2428 -- comments are no longer eatten by __future__ fixer. ........ r61673 | david.wolever | 2008-03-20 17:22:40 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Added 2to3 node pretty-printer ........ r61679 | david.wolever | 2008-03-20 20:50:42 +0100 (Do, 20 M?\195?\164r 2008) | 1 line Made node printing a little bit prettier ........ r61723 | martin.v.loewis | 2008-03-22 00:59:27 +0100 (Sa, 22 M?\195?\164r 2008) | 2 lines Fix whitespace. ........ ................ r61725 | martin.v.loewis | 2008-03-22 01:02:41 +0100 (Sat, 22 Mar 2008) | 2 lines Install lib2to3. ................ r61731 | facundo.batista | 2008-03-22 03:45:37 +0100 (Sat, 22 Mar 2008) | 4 lines Small fix that complicated the test actually when that test failed. ................ r61732 | alexandre.vassalotti | 2008-03-22 05:08:44 +0100 (Sat, 22 Mar 2008) | 2 lines Added warning for the removal of 'hotshot' in Py3k. ................ r61733 | georg.brandl | 2008-03-22 11:07:29 +0100 (Sat, 22 Mar 2008) | 4 lines #1918: document that weak references *to* an object are cleared before the object's __del__ is called, to ensure that the weak reference callback (if any) finds the object healthy. ................ r61734 | georg.brandl | 2008-03-22 11:56:23 +0100 (Sat, 22 Mar 2008) | 2 lines Activate the Sphinx doctest extension and convert howto/functional to use it. ................ r61735 | georg.brandl | 2008-03-22 11:58:38 +0100 (Sat, 22 Mar 2008) | 2 lines Allow giving source names on the cmdline. ................ r61737 | georg.brandl | 2008-03-22 12:00:48 +0100 (Sat, 22 Mar 2008) | 2 lines Fixup this HOWTO's doctest blocks so that they can be run with sphinx' doctest builder. ................ r61739 | georg.brandl | 2008-03-22 12:47:10 +0100 (Sat, 22 Mar 2008) | 2 lines Test decimal.rst doctests as far as possible with sphinx doctest. ................ r61741 | georg.brandl | 2008-03-22 13:04:26 +0100 (Sat, 22 Mar 2008) | 2 lines Make doctests in re docs usable with sphinx' doctest. ................ r61743 | georg.brandl | 2008-03-22 13:59:37 +0100 (Sat, 22 Mar 2008) | 2 lines Make more doctests in pprint docs testable. ................ r61744 | georg.brandl | 2008-03-22 14:07:06 +0100 (Sat, 22 Mar 2008) | 2 lines No need to specify explicit "doctest_block" anymore. ................ r61753 | georg.brandl | 2008-03-22 21:08:43 +0100 (Sat, 22 Mar 2008) | 2 lines Fix-up syntax problems. ................ r61761 | georg.brandl | 2008-03-22 22:06:20 +0100 (Sat, 22 Mar 2008) | 4 lines Make collections' doctests executable. (The <BLANKLINE>s will be stripped from presentation output.) ................ r61765 | georg.brandl | 2008-03-22 22:21:57 +0100 (Sat, 22 Mar 2008) | 2 lines Test doctests in datetime docs. ................ r61766 | georg.brandl | 2008-03-22 22:26:44 +0100 (Sat, 22 Mar 2008) | 2 lines Test doctests in operator docs. ................ r61767 | georg.brandl | 2008-03-22 22:38:33 +0100 (Sat, 22 Mar 2008) | 2 lines Enable doctests in functions.rst. Already found two errors :) ................ r61769 | georg.brandl | 2008-03-22 23:04:10 +0100 (Sat, 22 Mar 2008) | 3 lines Enable doctest running for several other documents. We have now over 640 doctests that are run with "make doctest". ................ r61773 | raymond.hettinger | 2008-03-23 01:55:46 +0100 (Sun, 23 Mar 2008) | 1 line Simplify demo code. ................ r61776 | neal.norwitz | 2008-03-23 04:43:33 +0100 (Sun, 23 Mar 2008) | 7 lines Try to make this test a little more robust and not fail with: timeout (10.0025) is more than 2 seconds more than expected (0.001) I'm assuming this problem is caused by DNS lookup. This change does a DNS lookup of the hostname before trying to connect, so the time is not included. ................ r61777 | neal.norwitz | 2008-03-23 05:08:30 +0100 (Sun, 23 Mar 2008) | 1 line Speed up the test by avoiding socket timeouts. ................ r61778 | neal.norwitz | 2008-03-23 05:43:09 +0100 (Sun, 23 Mar 2008) | 1 line Skip the epoll test if epoll() does not work ................ r61780 | neal.norwitz | 2008-03-23 06:47:20 +0100 (Sun, 23 Mar 2008) | 1 line Suppress failure (to avoid a flaky test) if we cannot connect to svn.python.org ................ r61781 | neal.norwitz | 2008-03-23 07:13:25 +0100 (Sun, 23 Mar 2008) | 4 lines Move itertools before future_builtins since the latter depends on the former. From a clean build importing future_builtins would fail since itertools wasn't built yet. ................ r61782 | neal.norwitz | 2008-03-23 07:16:04 +0100 (Sun, 23 Mar 2008) | 1 line Try to prevent the alarm going off early in tearDown ................ r61783 | neal.norwitz | 2008-03-23 07:19:57 +0100 (Sun, 23 Mar 2008) | 4 lines Remove compiler warnings (on Alpha at least) about using chars as array subscripts. Using chars are dangerous b/c they are signed on some platforms and unsigned on others. ................ r61788 | georg.brandl | 2008-03-23 09:05:30 +0100 (Sun, 23 Mar 2008) | 2 lines Make the doctests presentation-friendlier. ................ r61793 | amaury.forgeotdarc | 2008-03-23 10:55:29 +0100 (Sun, 23 Mar 2008) | 4 lines #1477: ur'\U0010FFFF' raised in narrow unicode builds. Corrected the raw-unicode-escape codec to use UTF-16 surrogates in this case, just like the unicode-escape codec. ................ r61796 | raymond.hettinger | 2008-03-23 14:32:32 +0100 (Sun, 23 Mar 2008) | 1 line Issue 1681432: Add triangular distribution the random module. ................ r61807 | raymond.hettinger | 2008-03-23 20:37:53 +0100 (Sun, 23 Mar 2008) | 4 lines Adopt Nick's suggestion for useful default arguments. Clean-up floating point issues by adding true division and float constants. ................ r61813 | gregory.p.smith | 2008-03-23 22:04:43 +0100 (Sun, 23 Mar 2008) | 6 lines Fix gzip to deal with CRC's being signed values in Python 2.x properly and to read 32bit values as unsigned to start with rather than applying signedness fixups allover the place afterwards. This hopefully fixes the test_tarfile failure on the alpha/tru64 buildbot. ................
2008-03-23 18:54:12 -03:00
2007-08-15 11:28:22 -03:00
.. function:: betavariate(alpha, beta)
Merged revisions 68633,68648,68667,68706,68718,68720-68721,68724-68727,68739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r68633 | thomas.heller | 2009-01-16 12:53:44 -0600 (Fri, 16 Jan 2009) | 3 lines Change an example in the docs to avoid a mistake when the code is copy pasted and changed afterwards. ........ r68648 | benjamin.peterson | 2009-01-16 22:28:57 -0600 (Fri, 16 Jan 2009) | 1 line use enumerate ........ r68667 | amaury.forgeotdarc | 2009-01-17 14:18:59 -0600 (Sat, 17 Jan 2009) | 3 lines #4077: No need to append \n when calling Py_FatalError + fix a declaration to make it match the one in pythonrun.h ........ r68706 | benjamin.peterson | 2009-01-17 19:28:46 -0600 (Sat, 17 Jan 2009) | 1 line fix grammar ........ r68718 | georg.brandl | 2009-01-18 04:42:35 -0600 (Sun, 18 Jan 2009) | 1 line #4976: union() and intersection() take multiple args, but talk about "the other". ........ r68720 | georg.brandl | 2009-01-18 04:45:22 -0600 (Sun, 18 Jan 2009) | 1 line #4974: fix redundant mention of lists and tuples. ........ r68721 | georg.brandl | 2009-01-18 04:48:16 -0600 (Sun, 18 Jan 2009) | 1 line #4914: trunc is in math. ........ r68724 | georg.brandl | 2009-01-18 07:24:10 -0600 (Sun, 18 Jan 2009) | 1 line #4979: correct result range for some random functions. ........ r68725 | georg.brandl | 2009-01-18 07:47:26 -0600 (Sun, 18 Jan 2009) | 1 line #4857: fix augmented assignment target spec. ........ r68726 | georg.brandl | 2009-01-18 08:41:52 -0600 (Sun, 18 Jan 2009) | 1 line #4923: clarify what was added. ........ r68727 | georg.brandl | 2009-01-18 12:25:30 -0600 (Sun, 18 Jan 2009) | 1 line #4986: augassigns are not expressions. ........ r68739 | benjamin.peterson | 2009-01-18 15:11:38 -0600 (Sun, 18 Jan 2009) | 1 line fix test that wasn't working as expected #4990 ........
2009-01-18 18:27:04 -04:00
Beta distribution. Conditions on the parameters are ``alpha > 0`` and
``beta > 0``. Returned values range between 0 and 1.
2007-08-15 11:28:22 -03:00
.. function:: expovariate(lambd = 1.0)
2007-08-15 11:28:22 -03:00
Exponential distribution. *lambd* 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 *lambd* is positive, and from
negative infinity to 0 if *lambd* is negative.
2007-08-15 11:28:22 -03:00
.. versionchanged:: 3.12
Added the default value for ``lambd``.
2007-08-15 11:28:22 -03:00
.. function:: gammavariate(alpha, beta)
Gamma distribution. (*Not* the gamma function!) The shape and
scale parameters, *alpha* and *beta*, must have positive values.
(Calling conventions vary and some sources define 'beta'
as the inverse of the scale).
2007-08-15 11:28:22 -03:00
The probability distribution function is::
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha
2007-08-15 11:28:22 -03:00
.. function:: gauss(mu=0.0, sigma=1.0)
2007-08-15 11:28:22 -03:00
Normal distribution, also called the Gaussian distribution.
*mu* is the mean,
and *sigma* is the standard deviation. This is slightly faster than
the :func:`normalvariate` function defined below.
2007-08-15 11:28:22 -03:00
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 :func:`normalvariate` function instead.
.. versionchanged:: 3.11
*mu* and *sigma* now have default arguments.
2007-08-15 11:28:22 -03:00
.. function:: lognormvariate(mu, sigma)
Log normal distribution. If you take the natural logarithm of this
distribution, you'll get a normal distribution with mean *mu* and standard
deviation *sigma*. *mu* can have any value, and *sigma* must be greater than
zero.
.. function:: normalvariate(mu=0.0, sigma=1.0)
2007-08-15 11:28:22 -03:00
Normal distribution. *mu* is the mean, and *sigma* is the standard deviation.
.. versionchanged:: 3.11
*mu* and *sigma* now have default arguments.
2007-08-15 11:28:22 -03:00
.. function:: vonmisesvariate(mu, kappa)
*mu* is the mean angle, expressed in radians between 0 and 2\*\ *pi*, and *kappa*
is the concentration parameter, which must be greater than or equal to zero. If
*kappa* is equal to zero, this distribution reduces to a uniform random angle
over the range 0 to 2\*\ *pi*.
.. function:: paretovariate(alpha)
Pareto distribution. *alpha* is the shape parameter.
.. function:: weibullvariate(alpha, beta)
Weibull distribution. *alpha* is the scale parameter and *beta* is the shape
parameter.
Alternative Generator
---------------------
2007-08-15 11:28:22 -03:00
.. class:: Random([seed])
Class that implements the default pseudo-random number generator used by the
:mod:`random` module.
.. versionchanged:: 3.11
Formerly the *seed* could be any hashable object. Now it is limited to:
``None``, :class:`int`, :class:`float`, :class:`str`,
:class:`bytes`, or :class:`bytearray`.
Subclasses of :class:`!Random` should override the following methods if they
wish to make use of a different basic generator:
.. method:: Random.seed(a=None, version=2)
Override this method in subclasses to customise the :meth:`~random.seed`
behaviour of :class:`!Random` instances.
.. method:: Random.getstate()
Override this method in subclasses to customise the :meth:`~random.getstate`
behaviour of :class:`!Random` instances.
.. method:: Random.setstate(state)
Override this method in subclasses to customise the :meth:`~random.setstate`
behaviour of :class:`!Random` instances.
.. method:: Random.random()
Override this method in subclasses to customise the :meth:`~random.random`
behaviour of :class:`!Random` instances.
Optionally, a custom generator subclass can also supply the following method:
.. method:: Random.getrandbits(k)
Override this method in subclasses to customise the
:meth:`~random.getrandbits` behaviour of :class:`!Random` instances.
2007-08-15 11:28:22 -03:00
.. class:: SystemRandom([seed])
Class that uses the :func:`os.urandom` function for generating random numbers
from sources provided by the operating system. Not available on all systems.
2010-12-02 01:35:35 -04:00
Does not rely on software state, and sequences are not reproducible. Accordingly,
the :meth:`seed` method has no effect and is ignored.
2007-08-15 11:28:22 -03:00
The :meth:`getstate` and :meth:`setstate` methods raise
:exc:`NotImplementedError` if called.
Notes on Reproducibility
2010-12-12 16:13:31 -04:00
------------------------
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.
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:
* If a new seeding method is added, then a backward compatible seeder will be
offered.
* The generator's :meth:`~Random.random` method will continue to produce the same
sequence when the compatible seeder is given the same seed.
2010-12-01 22:41:33 -04:00
2010-12-04 19:42:12 -04:00
.. _random-examples:
2010-12-01 22:41:33 -04:00
Examples
--------
2010-12-01 22:41:33 -04:00
Basic examples::
2010-12-02 01:35:35 -04:00
>>> random() # Random float: 0.0 <= x < 1.0
2010-12-02 01:35:35 -04:00
0.37444887175646646
>>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0
3.1800146073117523
2010-12-02 01:35:35 -04:00
>>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds
5.148957571865031
>>> randrange(10) # Integer from 0 to 9 inclusive
2010-12-02 01:35:35 -04:00
7
>>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
2010-12-02 01:35:35 -04:00
26
>>> choice(['win', 'lose', 'draw']) # Single random element from a sequence
'draw'
2010-12-02 01:35:35 -04:00
>>> 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, 30]
2010-12-02 01:35:35 -04:00
Simulations::
2010-12-02 01:35:35 -04:00
>>> # Six roulette wheel spins (weighted sampling with replacement)
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
['red', 'green', 'black', 'black', 'red', 'black']
2010-12-01 22:41:33 -04:00
>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value: ten, jack, queen, or king.
>>> deal = sample(['tens', 'low cards'], counts=[16, 36], k=20)
>>> deal.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.
>>> sum(binomialvariate(n=7, p=0.6) >= 5 for i in range(10_000)) / 10_000
0.4169
>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial():
... return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500
...
>>> sum(trial() for i in range(10_000)) / 10_000
0.7958
Example of `statistical bootstrapping
<https://en.wikipedia.org/wiki/Bootstrapping_(statistics)>`_ using resampling
with replacement to estimate a confidence interval for the mean of a sample::
2010-12-01 22:41:33 -04:00
# 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}')
Example of a `resampling permutation test
<https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests>`_
to determine the statistical significance or `p-value
<https://en.wikipedia.org/wiki/P-value>`_ of an observed difference
between the effects of a drug versus a placebo::
# 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 >= 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.')
Simulation of arrival times and service deliveries for a multiserver queue::
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)])
2020-10-13 20:41:26 -03:00
.. seealso::
`Statistics for Hackers <https://www.youtube.com/watch?v=Iq9DzN6mvYA>`_
a video tutorial by
`Jake Vanderplas <https://us.pycon.org/2016/speaker/profile/295/>`_
on statistical analysis using just a few fundamental concepts
including simulation, sampling, shuffling, and cross-validation.
`Economics Simulation
<https://nbviewer.org/url/norvig.com/ipython/Economics.ipynb>`_
2020-10-13 20:41:26 -03:00
a simulation of a marketplace by
`Peter Norvig <https://norvig.com/bio.html>`_ that shows effective
2020-10-13 20:41:26 -03:00
use 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)
<https://nbviewer.org/url/norvig.com/ipython/Probability.ipynb>`_
a tutorial by `Peter Norvig <https://norvig.com/bio.html>`_ covering
2020-10-13 20:41:26 -03:00
the basics of probability theory, how to write simulations, and
how to perform data analysis using Python.
Recipes
-------
These recipes show how to efficiently make random selections
from the combinatoric iterators in the :mod:`itertools` module:
.. testcode::
import random
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)
The default :func:`.random` returns multiples of 2⁻⁵³ in the range
2020-10-13 20:41:26 -03:00
*0.0 ≤ x < 1.0*. All such numbers are evenly spaced and are exactly
2020-10-15 03:41:55 -03:00
representable as Python floats. However, many other representable
floats 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 the
2020-10-13 20:41:26 -03:00
interval are possible selections. The mantissa comes from a uniform
distribution of integers in the range *2⁵² ≤ mantissa < 2⁵³*. The
exponent comes from a geometric distribution where exponents smaller
than *-53* occur half as often as the next larger exponent.
::
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)
2020-10-13 20:41:26 -03:00
All :ref:`real valued distributions <real-valued-distributions>`
in the class will use the new method::
>>> fr = FullRandom()
>>> fr.random()
0.05954861408025609
>>> fr.expovariate(0.25)
8.87925541791544
2020-10-13 20:41:26 -03:00
The recipe is conceptually equivalent to an algorithm that chooses from
all the multiples of 2⁻¹⁰⁷⁴ in the range *0.0 ≤ x < 1.0*. 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 ``math.ulp(0.0)``.)
2020-10-13 20:41:26 -03:00
.. seealso::
`Generating Pseudo-random Floating-Point Values
<https://allendowney.com/research/rand/downey07randfloat.pdf>`_ a
paper by Allen B. Downey describing ways to generate more
fine-grained floats than normally generated by :func:`.random`.
.. _random-cli:
Command-line usage
------------------
.. versionadded:: 3.13
The :mod:`!random` module can be executed from the command line.
.. code-block:: sh
python -m random [-h] [-c CHOICE [CHOICE ...] | -i N | -f N] [input ...]
The following options are accepted:
.. program:: random
.. option:: -h, --help
Show the help message and exit.
.. option:: -c CHOICE [CHOICE ...]
--choice CHOICE [CHOICE ...]
Print a random choice, using :meth:`choice`.
.. option:: -i <N>
--integer <N>
Print a random integer between 1 and N inclusive, using :meth:`randint`.
.. option:: -f <N>
--float <N>
Print a random floating-point number between 1 and N inclusive,
using :meth:`uniform`.
If no options are given, the output depends on the input:
* String or multiple: same as :option:`--choice`.
* Integer: same as :option:`--integer`.
* Float: same as :option:`--float`.
.. _random-cli-example:
Command-line example
--------------------
Here are some examples of the :mod:`!random` command-line interface:
.. code-block:: console
$ # Choose one at random
$ python -m random egg bacon sausage spam "Lobster Thermidor aux crevettes with a Mornay sauce"
Lobster Thermidor aux crevettes with a Mornay sauce
$ # Random integer
$ python -m random 6
6
$ # Random floating-point number
$ python -m random 1.8
1.7080016272295635
$ # With explicit arguments
$ python -m random --choice egg bacon sausage spam "Lobster Thermidor aux crevettes with a Mornay sauce"
egg
$ python -m random --integer 6
3
$ python -m random --float 1.8
1.5666339105010318
$ python -m random --integer 6
5
$ python -m random --float 6
3.1942323316565915