How does python generate 5 random numbers?

There is a need to generate random numbers when studying a model or behavior of a program for different range of values. Python can generate such random numbers by using the random module. In the below examples we will first see how to generate a single random number and then extend it to generate a list of random numbers.

Generating a Single Random Number

The random[] method in random module generates a float number between 0 and 1.

Example

import random
n = random.random[]
print[n]

Output

Running the above code gives us the following result −

0.2112200

Generating Number in a Range

The randint[] method generates a integer between a given range of numbers.

Example

import random
n = random.randint[0,22]
print[n]

Output

Running the above code gives us the following result −

2

Generating a List of numbers Using For Loop

We can use the above randint[] method along with a for loop to generate a list of numbers. We first create an empty list and then append the random numbers generated to the empty list one by one.

Example

import random
randomlist = []
for i in range[0,5]:
n = random.randint[1,30]
randomlist.append[n]
print[randomlist]

Output

Running the above code gives us the following result −

[10, 5, 21, 1, 17]

Using random.sample[]

We can also use the sample[] method available in random module to directly generate a list of random numbers.Here we specify a range and give how many random numbers we need to generate.

Example

import random
#Generate 5 random numbers between 10 and 30
randomlist = random.sample[range[10, 30], 5]
print[randomlist]

Output

Running the above code gives us the following result −

[16, 19, 13, 18, 15]

Updated on 08-Aug-2019 06:54:57

  • Related Questions & Answers
  • Generating Random Prime Number in JavaScript
  • Generating random number in a range in C
  • Generating random Id’s in Python
  • Generating random numbers in Java
  • Generating random numbers in C#
  • Generating Random String Using PHP
  • Generating Random id's using UUID in Python
  • Generating random hex color in JavaScript
  • Generating Random Short Id in Node.js
  • Generating a random number that is divisible by n in JavaScript
  • Generating random string of specified length in JavaScript
  • Generating random strings until a given string is generated using Python
  • Random Number Functions in Python
  • Generating n random numbers between a range - JavaScript
  • Generating random string with a specific length in JavaScript

Source code: Lib/random.py

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.

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 random[], which generates a random float uniformly in the semi-open range [0.0, 1.0]. Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the random[], seed[], getstate[], and setstate[] methods. Optionally, a new generator can supply a getrandbits[] method — this allows randrange[] to produce selections over an arbitrarily large range.

The random module also provides the SystemRandom class which uses the system function os.urandom[] to generate random numbers from sources provided by the operating system.

Warning

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

See also

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 for a compatible alternative random number generator with a long period and comparatively simple update operations.

Bookkeeping functions¶

random.seed[a=None, version=2]

Initialize the random number generator.

If a is omitted or None, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time [see the os.urandom[] function for details on availability].

If a is an int, it is used directly.

With version 2 [the default], a str, bytes, or bytearray object gets converted to an int and all of its bits are used.

With version 1 [provided for reproducing random sequences from older versions of Python], the algorithm for str and bytes generates a narrower range of seeds.

Changed in version 3.2: Moved to the version 2 scheme which uses all of the bits in a string seed.

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

random.getstate[]

Return an object capturing the current internal state of the generator. This object can be passed to setstate[] to restore the state.

random.setstate[state]

state should have been obtained from a previous call to getstate[], and setstate[] restores the internal state of the generator to what it was at the time getstate[] was called.

Functions for bytes¶

random.randbytes[n]

Generate n random bytes.

This method should not be used for generating security tokens. Use secrets.token_bytes[] instead.

New in version 3.9.

Functions for integers¶

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

Return a randomly selected element from range[start, stop, step]. This is equivalent to choice[range[start, stop, step]], but doesn’t actually build a range object.

The positional argument pattern matches that of range[]. Keyword arguments should not be used because the function may use them in unexpected ways.

Changed in version 3.2: randrange[] is more sophisticated about producing equally distributed values. Formerly it used a style like int[random[]*n] which could produce slightly uneven distributions.

Deprecated since version 3.10: The automatic conversion of non-integer types to equivalent integers is deprecated. Currently randrange[10.0] is losslessly converted to randrange[10]. In the future, this will raise a TypeError.

Deprecated since version 3.10: The exception raised for non-integral values such as randrange[10.5] or randrange['10'] will be changed from ValueError to TypeError.

random.randint[a, b]

Return a random integer N such that a expovariate[1 / 5] # Interval between arrivals averaging 5 seconds 5.148957571865031 >>> randrange[10] # Integer from 0 to 9 inclusive 7 >>> randrange[0, 101, 2] # Even integer from 0 to 100 inclusive 26 >>> choice[['win', 'lose', 'draw']] # Single random element from a sequence 'draw' >>> 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]

Simulations:

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # 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.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.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.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] 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 > sum[trial[] for i in range[10_000]] / 10_000
0.7958

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

# //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 to determine the statistical significance or 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]]]

See also

Statistics for Hackers a video tutorial by Jake Vanderplas on statistical analysis using just a few fundamental concepts including simulation, sampling, shuffling, and cross-validation.

Economics Simulation a simulation of a marketplace by Peter Norvig that shows effective 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] a tutorial by Peter Norvig covering the basics of probability theory, how to write simulations, and how to perform data analysis using Python.

Recipes¶

The default random[] returns multiples of 2⁻⁵³ in the range 0.0 ≤ x < 1.0. All such numbers are evenly spaced and are exactly representable as Python floats. However, many other representable floats in that interval are not possible selections. For example, 0.05954861408025609 isn’t an integer multiple of 2⁻⁵³.

The following recipe takes a different approach. All floats in the interval are possible selections. The mantissa comes from a uniform distribution of integers in the range 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]

All real valued distributions in the class will use the new method:

>>> fr = FullRandom[]
>>> fr.random[]
0.05954861408025609
>>> fr.expovariate[0.25]
8.87925541791544

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

How does Python generate random numbers?

Random integer values can be generated with the randint[] function. This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end].

How does Python generate 6 random numbers?

“how to generate 6 random number in a function in python” Code Answer.
# generate random integer values..
from random import randint..
value = randint[0, 10].
print[value].

How random numbers are generated?

A true random number generator [TRNG], also known as a hardware random number generator [HRNG], does not use a computer algorithm. Instead, it uses an external unpredictable physical variable such as radioactive decay of isotopes or airwave static to generate random numbers.

Chủ Đề