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 11This module implements pseudo-random number generators for various 12distributions. 13 14For integers, there is uniform selection from a range. For sequences, there is 15uniform selection of a random element, a function to generate a random 16permutation of a list in-place, and a function for random sampling without 17replacement. 18 19On the real line, there are functions to compute uniform, normal (Gaussian), 20lognormal, negative exponential, gamma, and beta distributions. For generating 21distributions of angles, the von Mises distribution is available. 22 23Almost all module functions depend on the basic function :func:`.random`, which 24generates a random float uniformly in the half-open range ``0.0 <= X < 1.0``. 25Python uses the Mersenne Twister as the core generator. It produces 53-bit precision 26floats and has a period of 2\*\*19937-1. The underlying implementation in C is 27both fast and threadsafe. The Mersenne Twister is one of the most extensively 28tested random number generators in existence. However, being completely 29deterministic, it is not suitable for all purposes, and is completely unsuitable 30for cryptographic purposes. 31 32The functions supplied by this module are actually bound methods of a hidden 33instance of the :class:`random.Random` class. You can instantiate your own 34instances of :class:`Random` to get generators that don't share state. 35 36Class :class:`Random` can also be subclassed if you want to use a different 37basic generator of your own devising: see the documentation on that class for 38more details. 39 40The :mod:`random` module also provides the :class:`SystemRandom` class which 41uses the system function :func:`os.urandom` to generate random numbers 42from 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 69Bookkeeping 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, it 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 111Functions 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 124Functions 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 168Functions 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 265Discrete distributions 266---------------------- 267 268The 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 290Real-valued distributions 291------------------------- 292 293The following functions generate specific real-valued distributions. Function 294parameters are named after the corresponding variables in the distribution's 295equation, as used in common mathematical practice; most of these equations can 296be 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 407Alternative 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 451.. class:: SystemRandom([seed]) 452 453 Class that uses the :func:`os.urandom` function for generating random numbers 454 from sources provided by the operating system. Not available on all systems. 455 Does not rely on software state, and sequences are not reproducible. Accordingly, 456 the :meth:`seed` method has no effect and is ignored. 457 The :meth:`getstate` and :meth:`setstate` methods raise 458 :exc:`NotImplementedError` if called. 459 460 461Notes on Reproducibility 462------------------------ 463 464Sometimes it is useful to be able to reproduce the sequences given by a 465pseudo-random number generator. By reusing a seed value, the same sequence should be 466reproducible from run to run as long as multiple threads are not running. 467 468Most of the random module's algorithms and seeding functions are subject to 469change across Python versions, but two aspects are guaranteed not to change: 470 471* If a new seeding method is added, then a backward compatible seeder will be 472 offered. 473 474* The generator's :meth:`~Random.random` method will continue to produce the same 475 sequence when the compatible seeder is given the same seed. 476 477.. _random-examples: 478 479Examples 480-------- 481 482Basic examples:: 483 484 >>> random() # Random float: 0.0 <= x < 1.0 485 0.37444887175646646 486 487 >>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0 488 3.1800146073117523 489 490 >>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds 491 5.148957571865031 492 493 >>> randrange(10) # Integer from 0 to 9 inclusive 494 7 495 496 >>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive 497 26 498 499 >>> choice(['win', 'lose', 'draw']) # Single random element from a sequence 500 'draw' 501 502 >>> deck = 'ace two three four'.split() 503 >>> shuffle(deck) # Shuffle a list 504 >>> deck 505 ['four', 'two', 'ace', 'three'] 506 507 >>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement 508 [40, 10, 50, 30] 509 510Simulations:: 511 512 >>> # Six roulette wheel spins (weighted sampling with replacement) 513 >>> choices(['red', 'black', 'green'], [18, 18, 2], k=6) 514 ['red', 'green', 'black', 'black', 'red', 'black'] 515 516 >>> # Deal 20 cards without replacement from a deck 517 >>> # of 52 playing cards, and determine the proportion of cards 518 >>> # with a ten-value: ten, jack, queen, or king. 519 >>> deal = sample(['tens', 'low cards'], counts=[16, 36], k=20) 520 >>> deal.count('tens') / 20 521 0.15 522 523 >>> # Estimate the probability of getting 5 or more heads from 7 spins 524 >>> # of a biased coin that settles on heads 60% of the time. 525 >>> sum(binomialvariate(n=7, p=0.6) >= 5 for i in range(10_000)) / 10_000 526 0.4169 527 528 >>> # Probability of the median of 5 samples being in middle two quartiles 529 >>> def trial(): 530 ... return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500 531 ... 532 >>> sum(trial() for i in range(10_000)) / 10_000 533 0.7958 534 535Example of `statistical bootstrapping 536<https://en.wikipedia.org/wiki/Bootstrapping_(statistics)>`_ using resampling 537with replacement to estimate a confidence interval for the mean of a sample:: 538 539 # https://www.thoughtco.com/example-of-bootstrapping-3126155 540 from statistics import fmean as mean 541 from random import choices 542 543 data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95] 544 means = sorted(mean(choices(data, k=len(data))) for i in range(100)) 545 print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' 546 f'interval from {means[5]:.1f} to {means[94]:.1f}') 547 548Example of a `resampling permutation test 549<https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests>`_ 550to determine the statistical significance or `p-value 551<https://en.wikipedia.org/wiki/P-value>`_ of an observed difference 552between the effects of a drug versus a placebo:: 553 554 # Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson 555 from statistics import fmean as mean 556 from random import shuffle 557 558 drug = [54, 73, 53, 70, 73, 68, 52, 65, 65] 559 placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46] 560 observed_diff = mean(drug) - mean(placebo) 561 562 n = 10_000 563 count = 0 564 combined = drug + placebo 565 for i in range(n): 566 shuffle(combined) 567 new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):]) 568 count += (new_diff >= observed_diff) 569 570 print(f'{n} label reshufflings produced only {count} instances with a difference') 571 print(f'at least as extreme as the observed difference of {observed_diff:.1f}.') 572 print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null') 573 print(f'hypothesis that there is no difference between the drug and the placebo.') 574 575Simulation of arrival times and service deliveries for a multiserver queue:: 576 577 from heapq import heapify, heapreplace 578 from random import expovariate, gauss 579 from statistics import mean, quantiles 580 581 average_arrival_interval = 5.6 582 average_service_time = 15.0 583 stdev_service_time = 3.5 584 num_servers = 3 585 586 waits = [] 587 arrival_time = 0.0 588 servers = [0.0] * num_servers # time when each server becomes available 589 heapify(servers) 590 for i in range(1_000_000): 591 arrival_time += expovariate(1.0 / average_arrival_interval) 592 next_server_available = servers[0] 593 wait = max(0.0, next_server_available - arrival_time) 594 waits.append(wait) 595 service_duration = max(0.0, gauss(average_service_time, stdev_service_time)) 596 service_completed = arrival_time + wait + service_duration 597 heapreplace(servers, service_completed) 598 599 print(f'Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}') 600 print('Quartiles:', [round(q, 1) for q in quantiles(waits)]) 601 602.. seealso:: 603 604 `Statistics for Hackers <https://www.youtube.com/watch?v=Iq9DzN6mvYA>`_ 605 a video tutorial by 606 `Jake Vanderplas <https://us.pycon.org/2016/speaker/profile/295/>`_ 607 on statistical analysis using just a few fundamental concepts 608 including simulation, sampling, shuffling, and cross-validation. 609 610 `Economics Simulation 611 <https://nbviewer.org/url/norvig.com/ipython/Economics.ipynb>`_ 612 a simulation of a marketplace by 613 `Peter Norvig <https://norvig.com/bio.html>`_ that shows effective 614 use of many of the tools and distributions provided by this module 615 (gauss, uniform, sample, betavariate, choice, triangular, and randrange). 616 617 `A Concrete Introduction to Probability (using Python) 618 <https://nbviewer.org/url/norvig.com/ipython/Probability.ipynb>`_ 619 a tutorial by `Peter Norvig <https://norvig.com/bio.html>`_ covering 620 the basics of probability theory, how to write simulations, and 621 how to perform data analysis using Python. 622 623 624Recipes 625------- 626 627These recipes show how to efficiently make random selections 628from the combinatoric iterators in the :mod:`itertools` module: 629 630.. testcode:: 631 import random 632 633 def random_product(*args, repeat=1): 634 "Random selection from itertools.product(*args, **kwds)" 635 pools = [tuple(pool) for pool in args] * repeat 636 return tuple(map(random.choice, pools)) 637 638 def random_permutation(iterable, r=None): 639 "Random selection from itertools.permutations(iterable, r)" 640 pool = tuple(iterable) 641 r = len(pool) if r is None else r 642 return tuple(random.sample(pool, r)) 643 644 def random_combination(iterable, r): 645 "Random selection from itertools.combinations(iterable, r)" 646 pool = tuple(iterable) 647 n = len(pool) 648 indices = sorted(random.sample(range(n), r)) 649 return tuple(pool[i] for i in indices) 650 651 def random_combination_with_replacement(iterable, r): 652 "Choose r elements with replacement. Order the result to match the iterable." 653 # Result will be in set(itertools.combinations_with_replacement(iterable, r)). 654 pool = tuple(iterable) 655 n = len(pool) 656 indices = sorted(random.choices(range(n), k=r)) 657 return tuple(pool[i] for i in indices) 658 659The default :func:`.random` returns multiples of 2⁻⁵³ in the range 660*0.0 ≤ x < 1.0*. All such numbers are evenly spaced and are exactly 661representable as Python floats. However, many other representable 662floats in that interval are not possible selections. For example, 663``0.05954861408025609`` isn't an integer multiple of 2⁻⁵³. 664 665The following recipe takes a different approach. All floats in the 666interval are possible selections. The mantissa comes from a uniform 667distribution of integers in the range *2⁵² ≤ mantissa < 2⁵³*. The 668exponent comes from a geometric distribution where exponents smaller 669than *-53* occur half as often as the next larger exponent. 670 671:: 672 673 from random import Random 674 from math import ldexp 675 676 class FullRandom(Random): 677 678 def random(self): 679 mantissa = 0x10_0000_0000_0000 | self.getrandbits(52) 680 exponent = -53 681 x = 0 682 while not x: 683 x = self.getrandbits(32) 684 exponent += x.bit_length() - 32 685 return ldexp(mantissa, exponent) 686 687All :ref:`real valued distributions <real-valued-distributions>` 688in the class will use the new method:: 689 690 >>> fr = FullRandom() 691 >>> fr.random() 692 0.05954861408025609 693 >>> fr.expovariate(0.25) 694 8.87925541791544 695 696The recipe is conceptually equivalent to an algorithm that chooses from 697all the multiples of 2⁻¹⁰⁷⁴ in the range *0.0 ≤ x < 1.0*. All such 698numbers are evenly spaced, but most have to be rounded down to the 699nearest representable Python float. (The value 2⁻¹⁰⁷⁴ is the smallest 700positive unnormalized float and is equal to ``math.ulp(0.0)``.) 701 702 703.. seealso:: 704 705 `Generating Pseudo-random Floating-Point Values 706 <https://allendowney.com/research/rand/downey07randfloat.pdf>`_ a 707 paper by Allen B. Downey describing ways to generate more 708 fine-grained floats than normally generated by :func:`.random`. 709 710.. _random-cli: 711 712Command-line usage 713------------------ 714 715.. versionadded:: 3.13 716 717The :mod:`!random` module can be executed from the command line. 718 719.. code-block:: sh 720 721 python -m random [-h] [-c CHOICE [CHOICE ...] | -i N | -f N] [input ...] 722 723The following options are accepted: 724 725.. program:: random 726 727.. option:: -h, --help 728 729 Show the help message and exit. 730 731.. option:: -c CHOICE [CHOICE ...] 732 --choice CHOICE [CHOICE ...] 733 734 Print a random choice, using :meth:`choice`. 735 736.. option:: -i <N> 737 --integer <N> 738 739 Print a random integer between 1 and N inclusive, using :meth:`randint`. 740 741.. option:: -f <N> 742 --float <N> 743 744 Print a random floating-point number between 0 and N inclusive, 745 using :meth:`uniform`. 746 747If no options are given, the output depends on the input: 748 749* String or multiple: same as :option:`--choice`. 750* Integer: same as :option:`--integer`. 751* Float: same as :option:`--float`. 752 753.. _random-cli-example: 754 755Command-line example 756-------------------- 757 758Here are some examples of the :mod:`!random` command-line interface: 759 760.. code-block:: console 761 762 $ # Choose one at random 763 $ python -m random egg bacon sausage spam "Lobster Thermidor aux crevettes with a Mornay sauce" 764 Lobster Thermidor aux crevettes with a Mornay sauce 765 766 $ # Random integer 767 $ python -m random 6 768 6 769 770 $ # Random floating-point number 771 $ python -m random 1.8 772 1.7080016272295635 773 774 $ # With explicit arguments 775 $ python -m random --choice egg bacon sausage spam "Lobster Thermidor aux crevettes with a Mornay sauce" 776 egg 777 778 $ python -m random --integer 6 779 3 780 781 $ python -m random --float 1.8 782 1.5666339105010318 783 784 $ python -m random --integer 6 785 5 786 787 $ python -m random --float 6 788 3.1942323316565915 789