| 1 |
:mod:`!random` --- Generate pseudo-random numbers |
| 2 |
================================================= |
| 3 |
|
| 4 |
.. module:: random |
| 5 |
:synopsis: Generate pseudo-random numbers with various common distributions. |
| 6 |
|
| 7 |
**Source code:** :source:`Lib/random.py` |
| 8 |
|
| 9 |
-------------- |
| 10 |
|
| 11 |
This module implements pseudo-random number generators for various |
| 12 |
distributions. |
| 13 |
|
| 14 |
For integers, there is uniform selection from a range. For sequences, there is |
| 15 |
uniform selection of a random element, a function to generate a random |
| 16 |
permutation of a list in-place, and a function for random sampling without |
| 17 |
replacement. |
| 18 |
|
| 19 |
On the real line, there are functions to compute uniform, normal (Gaussian), |
| 20 |
lognormal, negative exponential, gamma, and beta distributions. For generating |
| 21 |
distributions of angles, the von Mises distribution is available. |
| 22 |
|
| 23 |
Almost all module functions depend on the basic function :func:`.random`, which |
| 24 |
generates a random float uniformly in the half-open range ``0.0 <= X < 1.0``. |
| 25 |
Python uses the Mersenne Twister as the core generator. It produces 53-bit precision |
| 26 |
floats and has a period of 2\*\*19937-1. The underlying implementation in C is |
| 27 |
both fast and threadsafe. The Mersenne Twister is one of the most extensively |
| 28 |
tested random number generators in existence. However, being completely |
| 29 |
deterministic, it is not suitable for all purposes, and is completely unsuitable |
| 30 |
for cryptographic purposes. |
| 31 |
|
| 32 |
The functions supplied by this module are actually bound methods of a hidden |
| 33 |
instance of the :class:`random.Random` class. You can instantiate your own |
| 34 |
instances of :class:`Random` to get generators that don't share state. |
| 35 |
|
| 36 |
Class :class:`Random` can also be subclassed if you want to use a different |
| 37 |
basic generator of your own devising: see the documentation on that class for |
| 38 |
more details. |
| 39 |
|
| 40 |
The :mod:`!random` module also provides the :class:`SystemRandom` class which |
| 41 |
uses the system function :func:`os.urandom` to generate random numbers |
| 42 |
from sources provided by the operating system. |
| 43 |
|
| 44 |
.. warning:: |
| 45 |
|
| 46 |
The pseudo-random generators of this module should not be used for |
| 47 |
security purposes. For security or cryptographic uses, see the |
| 48 |
:mod:`secrets` module. |
| 49 |
|
| 50 |
.. seealso:: |
| 51 |
|
| 52 |
M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally |
| 53 |
equidistributed uniform pseudorandom number generator", ACM Transactions on |
| 54 |
Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998. |
| 55 |
|
| 56 |
|
| 57 |
`Complementary-Multiply-with-Carry recipe |
| 58 |
<https://code.activestate.com/recipes/576707-long-period-random-number-generator/>`_ for a compatible alternative |
| 59 |
random number generator with a long period and comparatively simple update |
| 60 |
operations. |
| 61 |
|
| 62 |
.. note:: |
| 63 |
The global random number generator and instances of :class:`Random` are thread-safe. |
| 64 |
However, in the free-threaded build, concurrent calls to the global generator or |
| 65 |
to the same instance of :class:`Random` may encounter contention and poor performance. |
| 66 |
Consider using separate instances of :class:`Random` per thread instead. |
| 67 |
|
| 68 |
|
| 69 |
Bookkeeping functions |
| 70 |
--------------------- |
| 71 |
|
| 72 |
.. function:: seed(a=None, version=2) |
| 73 |
|
| 74 |
Initialize the random number generator. |
| 75 |
|
| 76 |
If *a* is omitted or ``None``, the current system time is used. If |
| 77 |
randomness sources are provided by the operating system, they are used |
| 78 |
instead of the system time (see the :func:`os.urandom` function for details |
| 79 |
on availability). |
| 80 |
|
| 81 |
If *a* is an int, its absolute value is used directly. |
| 82 |
|
| 83 |
With version 2 (the default), a :class:`str`, :class:`bytes`, or :class:`bytearray` |
| 84 |
object gets converted to an :class:`int` and all of its bits are used. |
| 85 |
|
| 86 |
With version 1 (provided for reproducing random sequences from older versions |
| 87 |
of Python), the algorithm for :class:`str` and :class:`bytes` generates a |
| 88 |
narrower range of seeds. |
| 89 |
|
| 90 |
.. versionchanged:: 3.2 |
| 91 |
Moved to the version 2 scheme which uses all of the bits in a string seed. |
| 92 |
|
| 93 |
.. versionchanged:: 3.11 |
| 94 |
The *seed* must be one of the following types: |
| 95 |
``None``, :class:`int`, :class:`float`, :class:`str`, |
| 96 |
:class:`bytes`, or :class:`bytearray`. |
| 97 |
|
| 98 |
.. function:: getstate() |
| 99 |
|
| 100 |
Return an object capturing the current internal state of the generator. This |
| 101 |
object can be passed to :func:`setstate` to restore the state. |
| 102 |
|
| 103 |
|
| 104 |
.. function:: setstate(state) |
| 105 |
|
| 106 |
*state* should have been obtained from a previous call to :func:`getstate`, and |
| 107 |
:func:`setstate` restores the internal state of the generator to what it was at |
| 108 |
the time :func:`getstate` was called. |
| 109 |
|
| 110 |
|
| 111 |
Functions for bytes |
| 112 |
------------------- |
| 113 |
|
| 114 |
.. function:: randbytes(n) |
| 115 |
|
| 116 |
Generate *n* random bytes. |
| 117 |
|
| 118 |
This method should not be used for generating security tokens. |
| 119 |
Use :func:`secrets.token_bytes` instead. |
| 120 |
|
| 121 |
.. versionadded:: 3.9 |
| 122 |
|
| 123 |
|
| 124 |
Functions for integers |
| 125 |
---------------------- |
| 126 |
|
| 127 |
.. function:: randrange(stop) |
| 128 |
randrange(start, stop[, step]) |
| 129 |
|
| 130 |
Return a randomly selected element from ``range(start, stop, step)``. |
| 131 |
|
| 132 |
This is roughly equivalent to ``choice(range(start, stop, step))`` but |
| 133 |
supports arbitrarily large ranges and is optimized for common cases. |
| 134 |
|
| 135 |
The positional argument pattern matches the :func:`range` function. |
| 136 |
|
| 137 |
Keyword arguments should not be used because they can be interpreted |
| 138 |
in unexpected ways. For example ``randrange(start=100)`` is interpreted |
| 139 |
as ``randrange(0, 100, 1)``. |
| 140 |
|
| 141 |
.. versionchanged:: 3.2 |
| 142 |
:meth:`randrange` is more sophisticated about producing equally distributed |
| 143 |
values. Formerly it used a style like ``int(random()*n)`` which could produce |
| 144 |
slightly uneven distributions. |
| 145 |
|
| 146 |
.. versionchanged:: 3.12 |
| 147 |
Automatic conversion of non-integer types is no longer supported. |
| 148 |
Calls such as ``randrange(10.0)`` and ``randrange(Fraction(10, 1))`` |
| 149 |
now raise a :exc:`TypeError`. |
| 150 |
|
| 151 |
.. function:: randint(a, b) |
| 152 |
|
| 153 |
Return a random integer *N* such that ``a <= N <= b``. Alias for |
| 154 |
``randrange(a, b+1)``. |
| 155 |
|
| 156 |
.. function:: getrandbits(k) |
| 157 |
|
| 158 |
Returns a non-negative Python integer with *k* random bits. This method |
| 159 |
is supplied with the Mersenne Twister generator and some other generators |
| 160 |
may also provide it as an optional part of the API. When available, |
| 161 |
:meth:`getrandbits` enables :meth:`randrange` to handle arbitrarily large |
| 162 |
ranges. |
| 163 |
|
| 164 |
.. versionchanged:: 3.9 |
| 165 |
This method now accepts zero for *k*. |
| 166 |
|
| 167 |
|
| 168 |
Functions for sequences |
| 169 |
----------------------- |
| 170 |
|
| 171 |
.. function:: choice(seq) |
| 172 |
|
| 173 |
Return a random element from the non-empty sequence *seq*. If *seq* is empty, |
| 174 |
raises :exc:`IndexError`. |
| 175 |
|
| 176 |
.. function:: choices(population, weights=None, *, cum_weights=None, k=1) |
| 177 |
|
| 178 |
Return a *k* sized list of elements chosen from the *population* with replacement. |
| 179 |
If the *population* is empty, raises :exc:`IndexError`. |
| 180 |
|
| 181 |
If a *weights* sequence is specified, selections are made according to the |
| 182 |
relative weights. Alternatively, if a *cum_weights* sequence is given, the |
| 183 |
selections are made according to the cumulative weights (perhaps computed |
| 184 |
using :func:`itertools.accumulate`). For example, the relative weights |
| 185 |
``[10, 5, 30, 5]`` are equivalent to the cumulative weights |
| 186 |
``[10, 15, 45, 50]``. Internally, the relative weights are converted to |
| 187 |
cumulative weights before making selections, so supplying the cumulative |
| 188 |
weights saves work. |
| 189 |
|
| 190 |
If neither *weights* nor *cum_weights* are specified, selections are made |
| 191 |
with equal probability. If a weights sequence is supplied, it must be |
| 192 |
the same length as the *population* sequence. It is a :exc:`TypeError` |
| 193 |
to specify both *weights* and *cum_weights*. |
| 194 |
|
| 195 |
The *weights* or *cum_weights* can use any numeric type that interoperates |
| 196 |
with the :class:`float` values returned by :func:`random` (that includes |
| 197 |
integers, floats, and fractions but excludes decimals). Weights are assumed |
| 198 |
to be non-negative and finite. A :exc:`ValueError` is raised if all |
| 199 |
weights are zero. |
| 200 |
|
| 201 |
For a given seed, the :func:`choices` function with equal weighting |
| 202 |
typically produces a different sequence than repeated calls to |
| 203 |
:func:`choice`. The algorithm used by :func:`choices` uses floating-point |
| 204 |
arithmetic for internal consistency and speed. The algorithm used |
| 205 |
by :func:`choice` defaults to integer arithmetic with repeated selections |
| 206 |
to avoid small biases from round-off error. |
| 207 |
|
| 208 |
.. versionadded:: 3.6 |
| 209 |
|
| 210 |
.. versionchanged:: 3.9 |
| 211 |
Raises a :exc:`ValueError` if all weights are zero. |
| 212 |
|
| 213 |
|
| 214 |
.. function:: shuffle(x) |
| 215 |
|
| 216 |
Shuffle the sequence *x* in place. |
| 217 |
|
| 218 |
To shuffle an immutable sequence and return a new shuffled list, use |
| 219 |
``sample(x, k=len(x))`` instead. |
| 220 |
|
| 221 |
Note that even for small ``len(x)``, the total number of permutations of *x* |
| 222 |
can quickly grow larger than the period of most random number generators. |
| 223 |
This implies that most permutations of a long sequence can never be |
| 224 |
generated. For example, a sequence of length 2080 is the largest that |
| 225 |
can fit within the period of the Mersenne Twister random number generator. |
| 226 |
|
| 227 |
.. versionchanged:: 3.11 |
| 228 |
Removed the optional parameter *random*. |
| 229 |
|
| 230 |
|
| 231 |
.. function:: sample(population, k, *, counts=None) |
| 232 |
|
| 233 |
Return a *k* length list of unique elements chosen from the population |
| 234 |
sequence. Used for random sampling without replacement. |
| 235 |
|
| 236 |
Returns a new list containing elements from the population while leaving the |
| 237 |
original population unchanged. The resulting list is in selection order so that |
| 238 |
all sub-slices will also be valid random samples. This allows raffle winners |
| 239 |
(the sample) to be partitioned into grand prize and second place winners (the |
| 240 |
subslices). |
| 241 |
|
| 242 |
Members of the population need not be :term:`hashable` or unique. If the population |
| 243 |
contains repeats, then each occurrence is a possible selection in the sample. |
| 244 |
|
| 245 |
Repeated elements can be specified one at a time or with the optional |
| 246 |
keyword-only *counts* parameter. For example, ``sample(['red', 'blue'], |
| 247 |
counts=[4, 2], k=5)`` is equivalent to ``sample(['red', 'red', 'red', 'red', |
| 248 |
'blue', 'blue'], k=5)``. |
| 249 |
|
| 250 |
To choose a sample from a range of integers, use a :func:`range` object as an |
| 251 |
argument. This is especially fast and space efficient for sampling from a large |
| 252 |
population: ``sample(range(10000000), k=60)``. |
| 253 |
|
| 254 |
If the sample size is larger than the population size, a :exc:`ValueError` |
| 255 |
is raised. |
| 256 |
|
| 257 |
.. versionchanged:: 3.9 |
| 258 |
Added the *counts* parameter. |
| 259 |
|
| 260 |
.. versionchanged:: 3.11 |
| 261 |
|
| 262 |
The *population* must be a sequence. Automatic conversion of sets |
| 263 |
to lists is no longer supported. |
| 264 |
|
| 265 |
Discrete distributions |
| 266 |
---------------------- |
| 267 |
|
| 268 |
The following function generates a discrete distribution. |
| 269 |
|
| 270 |
.. function:: binomialvariate(n=1, p=0.5) |
| 271 |
|
| 272 |
`Binomial distribution |
| 273 |
<https://mathworld.wolfram.com/BinomialDistribution.html>`_. |
| 274 |
Return the number of successes for *n* independent trials with the |
| 275 |
probability of success in each trial being *p*: |
| 276 |
|
| 277 |
Mathematically equivalent to:: |
| 278 |
|
| 279 |
sum(random() < p for i in range(n)) |
| 280 |
|
| 281 |
The number of trials *n* should be a non-negative integer. |
| 282 |
The probability of success *p* should be between ``0.0 <= p <= 1.0``. |
| 283 |
The result is an integer in the range ``0 <= X <= n``. |
| 284 |
|
| 285 |
.. versionadded:: 3.12 |
| 286 |
|
| 287 |
|
| 288 |
.. _real-valued-distributions: |
| 289 |
|
| 290 |
Real-valued distributions |
| 291 |
------------------------- |
| 292 |
|
| 293 |
The following functions generate specific real-valued distributions. Function |
| 294 |
parameters are named after the corresponding variables in the distribution's |
| 295 |
equation, as used in common mathematical practice; most of these equations can |
| 296 |
be found in any statistics text. |
| 297 |
|
| 298 |
|
| 299 |
.. function:: random() |
| 300 |
|
| 301 |
Return the next random floating-point number in the range ``0.0 <= X < 1.0`` |
| 302 |
|
| 303 |
|
| 304 |
.. function:: uniform(a, b) |
| 305 |
|
| 306 |
Return a random floating-point number *N* such that ``a <= N <= b`` for |
| 307 |
``a <= b`` and ``b <= N <= a`` for ``b < a``. |
| 308 |
|
| 309 |
The end-point value ``b`` may or may not be included in the range |
| 310 |
depending on floating-point rounding in the expression |
| 311 |
``a + (b-a) * random()``. |
| 312 |
|
| 313 |
|
| 314 |
.. function:: triangular(low, high, mode) |
| 315 |
|
| 316 |
Return a random floating-point number *N* such that ``low <= N <= high`` and |
| 317 |
with the specified *mode* between those bounds. The *low* and *high* bounds |
| 318 |
default to zero and one. The *mode* argument defaults to the midpoint |
| 319 |
between the bounds, giving a symmetric distribution. |
| 320 |
|
| 321 |
|
| 322 |
.. function:: betavariate(alpha, beta) |
| 323 |
|
| 324 |
Beta distribution. Conditions on the parameters are ``alpha > 0`` and |
| 325 |
``beta > 0``. Returned values range between 0 and 1. |
| 326 |
|
| 327 |
|
| 328 |
.. function:: expovariate(lambd = 1.0) |
| 329 |
|
| 330 |
Exponential distribution. *lambd* is 1.0 divided by the desired |
| 331 |
mean. It should be nonzero. (The parameter would be called |
| 332 |
"lambda", but that is a reserved word in Python.) Returned values |
| 333 |
range from 0 to positive infinity if *lambd* is positive, and from |
| 334 |
negative infinity to 0 if *lambd* is negative. |
| 335 |
|
| 336 |
.. versionchanged:: 3.12 |
| 337 |
Added the default value for ``lambd``. |
| 338 |
|
| 339 |
|
| 340 |
.. function:: gammavariate(alpha, beta) |
| 341 |
|
| 342 |
Gamma distribution. (*Not* the gamma function!) The shape and |
| 343 |
scale parameters, *alpha* and *beta*, must have positive values. |
| 344 |
(Calling conventions vary and some sources define 'beta' |
| 345 |
as the inverse of the scale). |
| 346 |
|
| 347 |
The probability distribution function is:: |
| 348 |
|
| 349 |
x ** (alpha - 1) * math.exp(-x / beta) |
| 350 |
pdf(x) = -------------------------------------- |
| 351 |
math.gamma(alpha) * beta ** alpha |
| 352 |
|
| 353 |
|
| 354 |
.. function:: gauss(mu=0.0, sigma=1.0) |
| 355 |
|
| 356 |
Normal distribution, also called the Gaussian distribution. |
| 357 |
*mu* is the mean, |
| 358 |
and *sigma* is the standard deviation. This is slightly faster than |
| 359 |
the :func:`normalvariate` function defined below. |
| 360 |
|
| 361 |
Multithreading note: When two threads call this function |
| 362 |
simultaneously, it is possible that they will receive the |
| 363 |
same return value. This can be avoided in three ways. |
| 364 |
1) Have each thread use a different instance of the random |
| 365 |
number generator. 2) Put locks around all calls. 3) Use the |
| 366 |
slower, but thread-safe :func:`normalvariate` function instead. |
| 367 |
|
| 368 |
.. versionchanged:: 3.11 |
| 369 |
*mu* and *sigma* now have default arguments. |
| 370 |
|
| 371 |
|
| 372 |
.. function:: lognormvariate(mu, sigma) |
| 373 |
|
| 374 |
Log normal distribution. If you take the natural logarithm of this |
| 375 |
distribution, you'll get a normal distribution with mean *mu* and standard |
| 376 |
deviation *sigma*. *mu* can have any value, and *sigma* must be greater than |
| 377 |
zero. |
| 378 |
|
| 379 |
|
| 380 |
.. function:: normalvariate(mu=0.0, sigma=1.0) |
| 381 |
|
| 382 |
Normal distribution. *mu* is the mean, and *sigma* is the standard deviation. |
| 383 |
|
| 384 |
.. versionchanged:: 3.11 |
| 385 |
*mu* and *sigma* now have default arguments. |
| 386 |
|
| 387 |
|
| 388 |
.. function:: vonmisesvariate(mu, kappa) |
| 389 |
|
| 390 |
*mu* is the mean angle, expressed in radians between 0 and 2\*\ *pi*, and *kappa* |
| 391 |
is the concentration parameter, which must be greater than or equal to zero. If |
| 392 |
*kappa* is equal to zero, this distribution reduces to a uniform random angle |
| 393 |
over the range 0 to 2\*\ *pi*. |
| 394 |
|
| 395 |
|
| 396 |
.. function:: paretovariate(alpha) |
| 397 |
|
| 398 |
Pareto distribution. *alpha* is the shape parameter. |
| 399 |
|
| 400 |
|
| 401 |
.. function:: weibullvariate(alpha, beta) |
| 402 |
|
| 403 |
Weibull distribution. *alpha* is the scale parameter and *beta* is the shape |
| 404 |
parameter. |
| 405 |
|
| 406 |
|
| 407 |
Alternative Generator |
| 408 |
--------------------- |
| 409 |
|
| 410 |
.. class:: Random([seed]) |
| 411 |
|
| 412 |
Class that implements the default pseudo-random number generator used by the |
| 413 |
:mod:`!random` module. |
| 414 |
|
| 415 |
.. versionchanged:: 3.11 |
| 416 |
Formerly the *seed* could be any hashable object. Now it is limited to: |
| 417 |
``None``, :class:`int`, :class:`float`, :class:`str`, |
| 418 |
:class:`bytes`, or :class:`bytearray`. |
| 419 |
|
| 420 |
Subclasses of :class:`!Random` should override the following methods if they |
| 421 |
wish to make use of a different basic generator: |
| 422 |
|
| 423 |
.. method:: Random.seed(a=None, version=2) |
| 424 |
|
| 425 |
Override this method in subclasses to customise the :meth:`~random.seed` |
| 426 |
behaviour of :class:`!Random` instances. |
| 427 |
|
| 428 |
.. method:: Random.getstate() |
| 429 |
|
| 430 |
Override this method in subclasses to customise the :meth:`~random.getstate` |
| 431 |
behaviour of :class:`!Random` instances. |
| 432 |
|
| 433 |
.. method:: Random.setstate(state) |
| 434 |
|
| 435 |
Override this method in subclasses to customise the :meth:`~random.setstate` |
| 436 |
behaviour of :class:`!Random` instances. |
| 437 |
|
| 438 |
.. method:: Random.random() |
| 439 |
|
| 440 |
Override this method in subclasses to customise the :meth:`~random.random` |
| 441 |
behaviour of :class:`!Random` instances. |
| 442 |
|
| 443 |
Optionally, a custom generator subclass can also supply the following method: |
| 444 |
|
| 445 |
.. method:: Random.getrandbits(k) |
| 446 |
|
| 447 |
Override this method in subclasses to customise the |
| 448 |
:meth:`~random.getrandbits` behaviour of :class:`!Random` instances. |
| 449 |
|
| 450 |
.. method:: Random.randbytes(n) |
| 451 |
|
| 452 |
Override this method in subclasses to customise the |
| 453 |
:meth:`~random.randbytes` behaviour of :class:`!Random` instances. |
| 454 |
|
| 455 |
|
| 456 |
.. class:: SystemRandom([seed]) |
| 457 |
|
| 458 |
Class that uses the :func:`os.urandom` function for generating random numbers |
| 459 |
from sources provided by the operating system. Not available on all systems. |
| 460 |
Does not rely on software state, and sequences are not reproducible. Accordingly, |
| 461 |
the :meth:`seed` method has no effect and is ignored. |
| 462 |
The :meth:`getstate` and :meth:`setstate` methods raise |
| 463 |
:exc:`NotImplementedError` if called. |
| 464 |
|
| 465 |
|
| 466 |
Notes on Reproducibility |
| 467 |
------------------------ |
| 468 |
|
| 469 |
Sometimes it is useful to be able to reproduce the sequences given by a |
| 470 |
pseudo-random number generator. By reusing a seed value, the same sequence should be |
| 471 |
reproducible from run to run as long as multiple threads are not running. |
| 472 |
|
| 473 |
Most of the random module's algorithms and seeding functions are subject to |
| 474 |
change across Python versions, but two aspects are guaranteed not to change: |
| 475 |
|
| 476 |
* If a new seeding method is added, then a backward compatible seeder will be |
| 477 |
offered. |
| 478 |
|
| 479 |
* The generator's :meth:`~Random.random` method will continue to produce the same |
| 480 |
sequence when the compatible seeder is given the same seed. |
| 481 |
|
| 482 |
.. _random-examples: |
| 483 |
|
| 484 |
Examples |
| 485 |
-------- |
| 486 |
|
| 487 |
Basic examples:: |
| 488 |
|
| 489 |
>>> random() # Random float: 0.0 <= x < 1.0 |
| 490 |
0.37444887175646646 |
| 491 |
|
| 492 |
>>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0 |
| 493 |
3.1800146073117523 |
| 494 |
|
| 495 |
>>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds |
| 496 |
5.148957571865031 |
| 497 |
|
| 498 |
>>> randrange(10) # Integer from 0 to 9 inclusive |
| 499 |
7 |
| 500 |
|
| 501 |
>>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive |
| 502 |
26 |
| 503 |
|
| 504 |
>>> choice(['win', 'lose', 'draw']) # Single random element from a sequence |
| 505 |
'draw' |
| 506 |
|
| 507 |
>>> deck = 'ace two three four'.split() |
| 508 |
>>> shuffle(deck) # Shuffle a list |
| 509 |
>>> deck |
| 510 |
['four', 'two', 'ace', 'three'] |
| 511 |
|
| 512 |
>>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement |
| 513 |
[40, 10, 50, 30] |
| 514 |
|
| 515 |
Simulations:: |
| 516 |
|
| 517 |
>>> # Six roulette wheel spins (weighted sampling with replacement) |
| 518 |
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6) |
| 519 |
['red', 'green', 'black', 'black', 'red', 'black'] |
| 520 |
|
| 521 |
>>> # Deal 20 cards without replacement from a deck |
| 522 |
>>> # of 52 playing cards, and determine the proportion of cards |
| 523 |
>>> # with a ten-value: ten, jack, queen, or king. |
| 524 |
>>> deal = sample(['tens', 'low cards'], counts=[16, 36], k=20) |
| 525 |
>>> deal.count('tens') / 20 |
| 526 |
0.15 |
| 527 |
|
| 528 |
>>> # Estimate the probability of getting 5 or more heads from 7 spins |
| 529 |
>>> # of a biased coin that settles on heads 60% of the time. |
| 530 |
>>> sum(binomialvariate(n=7, p=0.6) >= 5 for i in range(10_000)) / 10_000 |
| 531 |
0.4169 |
| 532 |
|
| 533 |
>>> # Probability of the median of 5 samples being in middle two quartiles |
| 534 |
>>> def trial(): |
| 535 |
... return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500 |
| 536 |
... |
| 537 |
>>> sum(trial() for i in range(10_000)) / 10_000 |
| 538 |
0.7958 |
| 539 |
|
| 540 |
Example of `statistical bootstrapping |
| 541 |
<https://en.wikipedia.org/wiki/Bootstrapping_(statistics)>`_ using resampling |
| 542 |
with replacement to estimate a confidence interval for the mean of a sample:: |
| 543 |
|
| 544 |
# https://www.thoughtco.com/example-of-bootstrapping-3126155 |
| 545 |
from statistics import fmean as mean |
| 546 |
from random import choices |
| 547 |
|
| 548 |
data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95] |
| 549 |
means = sorted(mean(choices(data, k=len(data))) for i in range(100)) |
| 550 |
print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' |
| 551 |
f'interval from {means[5]:.1f} to {means[94]:.1f}') |
| 552 |
|
| 553 |
Example of a `resampling permutation test |
| 554 |
<https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests>`_ |
| 555 |
to determine the statistical significance or `p-value |
| 556 |
<https://en.wikipedia.org/wiki/P-value>`_ of an observed difference |
| 557 |
between the effects of a drug versus a placebo:: |
| 558 |
|
| 559 |
# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson |
| 560 |
from statistics import fmean as mean |
| 561 |
from random import shuffle |
| 562 |
|
| 563 |
drug = [54, 73, 53, 70, 73, 68, 52, 65, 65] |
| 564 |
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46] |
| 565 |
observed_diff = mean(drug) - mean(placebo) |
| 566 |
|
| 567 |
n = 10_000 |
| 568 |
count = 0 |
| 569 |
combined = drug + placebo |
| 570 |
for i in range(n): |
| 571 |
shuffle(combined) |
| 572 |
new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):]) |
| 573 |
count += (new_diff >= observed_diff) |
| 574 |
|
| 575 |
print(f'{n} label reshufflings produced only {count} instances with a difference') |
| 576 |
print(f'at least as extreme as the observed difference of {observed_diff:.1f}.') |
| 577 |
print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null') |
| 578 |
print(f'hypothesis that there is no difference between the drug and the placebo.') |
| 579 |
|
| 580 |
Simulation of arrival times and service deliveries for a multiserver queue:: |
| 581 |
|
| 582 |
from heapq import heapify, heapreplace |
| 583 |
from random import expovariate, gauss |
| 584 |
from statistics import mean, quantiles |
| 585 |
|
| 586 |
average_arrival_interval = 5.6 |
| 587 |
average_service_time = 15.0 |
| 588 |
stdev_service_time = 3.5 |
| 589 |
num_servers = 3 |
| 590 |
|
| 591 |
waits = [] |
| 592 |
arrival_time = 0.0 |
| 593 |
servers = [0.0] * num_servers # time when each server becomes available |
| 594 |
heapify(servers) |
| 595 |
for i in range(1_000_000): |
| 596 |
arrival_time += expovariate(1.0 / average_arrival_interval) |
| 597 |
next_server_available = servers[0] |
| 598 |
wait = max(0.0, next_server_available - arrival_time) |
| 599 |
waits.append(wait) |
| 600 |
service_duration = max(0.0, gauss(average_service_time, stdev_service_time)) |
| 601 |
service_completed = arrival_time + wait + service_duration |
| 602 |
heapreplace(servers, service_completed) |
| 603 |
|
| 604 |
print(f'Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}') |
| 605 |
print('Quartiles:', [round(q, 1) for q in quantiles(waits)]) |
| 606 |
|
| 607 |
.. seealso:: |
| 608 |
|
| 609 |
`Statistics for Hackers <https://www.youtube.com/watch?v=Iq9DzN6mvYA>`_ |
| 610 |
a video tutorial by |
| 611 |
`Jake Vanderplas <https://us.pycon.org/2016/speaker/profile/295/>`_ |
| 612 |
on statistical analysis using just a few fundamental concepts |
| 613 |
including simulation, sampling, shuffling, and cross-validation. |
| 614 |
|
| 615 |
`Economics Simulation |
| 616 |
<https://nbviewer.org/url/norvig.com/ipython/Economics.ipynb>`_ |
| 617 |
a simulation of a marketplace by |
| 618 |
`Peter Norvig <https://norvig.com/bio.html>`_ that shows effective |
| 619 |
use of many of the tools and distributions provided by this module |
| 620 |
(gauss, uniform, sample, betavariate, choice, triangular, and randrange). |
| 621 |
|
| 622 |
`A Concrete Introduction to Probability (using Python) |
| 623 |
<https://nbviewer.org/url/norvig.com/ipython/Probability.ipynb>`_ |
| 624 |
a tutorial by `Peter Norvig <https://norvig.com/bio.html>`_ covering |
| 625 |
the basics of probability theory, how to write simulations, and |
| 626 |
how to perform data analysis using Python. |
| 627 |
|
| 628 |
|
| 629 |
Recipes |
| 630 |
------- |
| 631 |
|
| 632 |
These recipes show how to efficiently make random selections |
| 633 |
from the combinatoric iterators in the :mod:`itertools` module: |
| 634 |
|
| 635 |
.. testcode:: |
| 636 |
|
| 637 |
import random |
| 638 |
|
| 639 |
def random_product(*iterables, repeat=1): |
| 640 |
"Random selection from itertools.product(*iterables, repeat=repeat)" |
| 641 |
pools = tuple(map(tuple, iterables)) * repeat |
| 642 |
return tuple(map(random.choice, pools)) |
| 643 |
|
| 644 |
def random_permutation(iterable, r=None): |
| 645 |
"Random selection from itertools.permutations(iterable, r)" |
| 646 |
pool = tuple(iterable) |
| 647 |
r = len(pool) if r is None else r |
| 648 |
return tuple(random.sample(pool, r)) |
| 649 |
|
| 650 |
def random_combination(iterable, r): |
| 651 |
"Random selection from itertools.combinations(iterable, r)" |
| 652 |
pool = tuple(iterable) |
| 653 |
n = len(pool) |
| 654 |
indices = sorted(random.sample(range(n), r)) |
| 655 |
return tuple(pool[i] for i in indices) |
| 656 |
|
| 657 |
def random_combination_with_replacement(iterable, r): |
| 658 |
"Choose r elements with replacement. Order the result to match the iterable." |
| 659 |
# Result will be in set(itertools.combinations_with_replacement(iterable, r)). |
| 660 |
pool = tuple(iterable) |
| 661 |
n = len(pool) |
| 662 |
indices = sorted(random.choices(range(n), k=r)) |
| 663 |
return tuple(pool[i] for i in indices) |
| 664 |
|
| 665 |
def random_derangement(iterable): |
| 666 |
"Choose a permutation where no element stays in its original position." |
| 667 |
seq = tuple(iterable) |
| 668 |
if len(seq) < 2: |
| 669 |
if not seq: |
| 670 |
return () |
| 671 |
raise IndexError('No derangments to choose from') |
| 672 |
perm = list(range(len(seq))) |
| 673 |
start = tuple(perm) |
| 674 |
while True: |
| 675 |
random.shuffle(perm) |
| 676 |
if all(p != q for p, q in zip(start, perm)): |
| 677 |
return tuple([seq[i] for i in perm]) |
| 678 |
|
| 679 |
.. doctest:: |
| 680 |
:hide: |
| 681 |
|
| 682 |
>>> import random |
| 683 |
|
| 684 |
|
| 685 |
>>> random.seed(8675309) |
| 686 |
>>> random_product('ABCDEFG', repeat=5) |
| 687 |
('D', 'B', 'E', 'F', 'E') |
| 688 |
|
| 689 |
|
| 690 |
>>> random.seed(8675309) |
| 691 |
>>> random_permutation('ABCDEFG') |
| 692 |
('D', 'B', 'E', 'C', 'G', 'A', 'F') |
| 693 |
>>> random_permutation('ABCDEFG', 5) |
| 694 |
('A', 'G', 'D', 'C', 'B') |
| 695 |
|
| 696 |
|
| 697 |
>>> random.seed(8675309) |
| 698 |
>>> random_combination('ABCDEFG', 7) |
| 699 |
('A', 'B', 'C', 'D', 'E', 'F', 'G') |
| 700 |
>>> random_combination('ABCDEFG', 6) |
| 701 |
('A', 'B', 'C', 'D', 'F', 'G') |
| 702 |
>>> random_combination('ABCDEFG', 5) |
| 703 |
('A', 'B', 'C', 'E', 'F') |
| 704 |
>>> random_combination('ABCDEFG', 4) |
| 705 |
('B', 'C', 'D', 'G') |
| 706 |
>>> random_combination('ABCDEFG', 3) |
| 707 |
('B', 'E', 'G') |
| 708 |
>>> random_combination('ABCDEFG', 2) |
| 709 |
('E', 'G') |
| 710 |
>>> random_combination('ABCDEFG', 1) |
| 711 |
('C',) |
| 712 |
>>> random_combination('ABCDEFG', 0) |
| 713 |
() |
| 714 |
|
| 715 |
|
| 716 |
>>> random.seed(8675309) |
| 717 |
>>> random_combination_with_replacement('ABCDEFG', 7) |
| 718 |
('B', 'C', 'D', 'E', 'E', 'E', 'G') |
| 719 |
>>> random_combination_with_replacement('ABCDEFG', 3) |
| 720 |
('A', 'B', 'E') |
| 721 |
>>> random_combination_with_replacement('ABCDEFG', 2) |
| 722 |
('A', 'G') |
| 723 |
>>> random_combination_with_replacement('ABCDEFG', 1) |
| 724 |
('E',) |
| 725 |
>>> random_combination_with_replacement('ABCDEFG', 0) |
| 726 |
() |
| 727 |
|
| 728 |
|
| 729 |
>>> random.seed(8675309) |
| 730 |
>>> random_derangement('') |
| 731 |
() |
| 732 |
>>> random_derangement('A') |
| 733 |
Traceback (most recent call last): |
| 734 |
... |
| 735 |
IndexError: No derangments to choose from |
| 736 |
>>> random_derangement('AB') |
| 737 |
('B', 'A') |
| 738 |
>>> random_derangement('ABC') |
| 739 |
('C', 'A', 'B') |
| 740 |
>>> random_derangement('ABCD') |
| 741 |
('B', 'A', 'D', 'C') |
| 742 |
>>> random_derangement('ABCDE') |
| 743 |
('B', 'C', 'A', 'E', 'D') |
| 744 |
>>> # Identical inputs treated as distinct |
| 745 |
>>> identical = 20 |
| 746 |
>>> random_derangement((10, identical, 30, identical)) |
| 747 |
(20, 30, 10, 20) |
| 748 |
|
| 749 |
|
| 750 |
The default :func:`.random` returns multiples of 2⁻⁵³ in the range |
| 751 |
*0.0 ≤ x < 1.0*. All such numbers are evenly spaced and are exactly |
| 752 |
representable as Python floats. However, many other representable |
| 753 |
floats in that interval are not possible selections. For example, |
| 754 |
``0.05954861408025609`` isn't an integer multiple of 2⁻⁵³. |
| 755 |
|
| 756 |
The following recipe takes a different approach. All floats in the |
| 757 |
interval are possible selections. The mantissa comes from a uniform |
| 758 |
distribution of integers in the range *2⁵² ≤ mantissa < 2⁵³*. The |
| 759 |
exponent comes from a geometric distribution where exponents smaller |
| 760 |
than *-53* occur half as often as the next larger exponent. |
| 761 |
|
| 762 |
:: |
| 763 |
|
| 764 |
from random import Random |
| 765 |
from math import ldexp |
| 766 |
|
| 767 |
class FullRandom(Random): |
| 768 |
|
| 769 |
def random(self): |
| 770 |
mantissa = 0x10_0000_0000_0000 | self.getrandbits(52) |
| 771 |
exponent = -53 |
| 772 |
x = 0 |
| 773 |
while not x: |
| 774 |
x = self.getrandbits(32) |
| 775 |
exponent += x.bit_length() - 32 |
| 776 |
return ldexp(mantissa, exponent) |
| 777 |
|
| 778 |
All :ref:`real valued distributions <real-valued-distributions>` |
| 779 |
in the class will use the new method:: |
| 780 |
|
| 781 |
>>> fr = FullRandom() |
| 782 |
>>> fr.random() |
| 783 |
0.05954861408025609 |
| 784 |
>>> fr.expovariate(0.25) |
| 785 |
8.87925541791544 |
| 786 |
|
| 787 |
The recipe is conceptually equivalent to an algorithm that chooses from |
| 788 |
all the multiples of 2⁻¹⁰⁷⁴ in the range *0.0 ≤ x < 1.0*. All such |
| 789 |
numbers are evenly spaced, but most have to be rounded down to the |
| 790 |
nearest representable Python float. (The value 2⁻¹⁰⁷⁴ is the smallest |
| 791 |
positive unnormalized float and is equal to ``math.ulp(0.0)``.) |
| 792 |
|
| 793 |
|
| 794 |
.. seealso:: |
| 795 |
|
| 796 |
`Generating Pseudo-random Floating-Point Values |
| 797 |
<https://allendowney.com/research/rand/downey07randfloat.pdf>`_ a |
| 798 |
paper by Allen B. Downey describing ways to generate more |
| 799 |
fine-grained floats than normally generated by :func:`.random`. |
| 800 |
|
| 801 |
.. _random-cli: |
| 802 |
|
| 803 |
Command-line usage |
| 804 |
------------------ |
| 805 |
|
| 806 |
.. versionadded:: 3.13 |
| 807 |
|
| 808 |
The :mod:`!random` module can be executed from the command line. |
| 809 |
|
| 810 |
.. code-block:: sh |
| 811 |
|
| 812 |
python -m random [-h] [-c CHOICE [CHOICE ...] | -i N | -f N] [input ...] |
| 813 |
|
| 814 |
The following options are accepted: |
| 815 |
|
| 816 |
.. program:: random |
| 817 |
|
| 818 |
.. option:: -h, --help |
| 819 |
|
| 820 |
Show the help message and exit. |
| 821 |
|
| 822 |
.. option:: -c CHOICE [CHOICE ...] |
| 823 |
--choice CHOICE [CHOICE ...] |
| 824 |
|
| 825 |
Print a random choice, using :meth:`choice`. |
| 826 |
|
| 827 |
.. option:: -i <N> |
| 828 |
--integer <N> |
| 829 |
|
| 830 |
Print a random integer between 1 and N inclusive, using :meth:`randint`. |
| 831 |
|
| 832 |
.. option:: -f <N> |
| 833 |
--float <N> |
| 834 |
|
| 835 |
Print a random floating-point number between 0 and N inclusive, |
| 836 |
using :meth:`uniform`. |
| 837 |
|
| 838 |
If no options are given, the output depends on the input: |
| 839 |
|
| 840 |
* String or multiple: same as :option:`--choice`. |
| 841 |
* Integer: same as :option:`--integer`. |
| 842 |
* Float: same as :option:`--float`. |
| 843 |
|
| 844 |
.. _random-cli-example: |
| 845 |
|
| 846 |
Command-line example |
| 847 |
-------------------- |
| 848 |
|
| 849 |
Here are some examples of the :mod:`!random` command-line interface: |
| 850 |
|
| 851 |
.. code-block:: console |
| 852 |
|
| 853 |
$ # Choose one at random |
| 854 |
$ python -m random egg bacon sausage spam "Lobster Thermidor aux crevettes with a Mornay sauce" |
| 855 |
Lobster Thermidor aux crevettes with a Mornay sauce |
| 856 |
|
| 857 |
$ # Random integer |
| 858 |
$ python -m random 6 |
| 859 |
6 |
| 860 |
|
| 861 |
$ # Random floating-point number |
| 862 |
$ python -m random 1.8 |
| 863 |
1.7080016272295635 |
| 864 |
|
| 865 |
$ # With explicit arguments |
| 866 |
$ python -m random --choice egg bacon sausage spam "Lobster Thermidor aux crevettes with a Mornay sauce" |
| 867 |
egg |
| 868 |
|
| 869 |
$ python -m random --integer 6 |
| 870 |
3 |
| 871 |
|
| 872 |
$ python -m random --float 1.8 |
| 873 |
1.5666339105010318 |
| 874 |
|
| 875 |
$ python -m random --integer 6 |
| 876 |
5 |
| 877 |
|
| 878 |
$ python -m random --float 6 |
| 879 |
3.1942323316565915 |