Python random module provided implementations of generating pseudo-random numbers for various distribution.
It provides functions to generate below distributions:
Python's Pseudo-Random Numbers Generator (PRNG) is based on Mersenne Twister. It's a deterministic generator and hence not suitable for all situations. For cryptography purposes, please use secrets
module.
import random
import matplotlib.pyplot as plt
%matplotlib inline
random.random() ## random() generates random floating number in range [0,1.0)
randint(a,b)
- Generates random integer in range a <= integer<=brandrandge(stop)
, randrange(start,stop [,step])
- generates range of random numbers in range start and stop with steps.choice(sequence)
- Select one number randomly from sequence.choices(population, weights=None,cum_weights=None, k=1)
- Selects list of k
random numbers with replacement means that it can return repeated
numbers. weights
and cum_weights
can be used to select random numbers based on priority. Either weight
or cum_weights
should be supplied. Length of weights
or cum_weights
should be asem as population list.shuffle(x[, random])
- Shuffle random numbers in place. Can not use it with immutable sequence. Use sample()
function for shuffling immutable sequence.sample(population, k)
- Randomly sample k items from population.getrandbits(k)
- Generates integer with random k bits. Can be used to generate random numbers with bits limitation.print(random.randint(1,10))
print(random.randrange(10))
print(random.randrange(1, 10))
print(random.randrange(1,10, 2))
print(random.choice(range(10)))
print(random.choices(range(20), k=5))
x = list(range(5,55,5))
print('Before shuffling x : '+str(x))
random.shuffle(x)
print('After shuffling x : '+str(x))
x1 = random.sample(x, 5)
print(x1)
## Below will output numbers more from begining because weights are set to [9,8,7,6,5,4,3,2,1,0] if you run choices more than one.
print(random.choices(range(10), weights = reversed(range(10)), k = 2))
print(random.getrandbits(10))
Below is a list of functions that can be used to generate the same results using random numbers. It can help different users to reproduce the same results in research.
seed(a=None, version=2)
- This function initializes random number generator with seed so that it produces the same result which can be used for reproducing results.a
is not provided then current system time is used.a
can be any integer.version
has 2 values (1 & 2). With version 2 , str
, byte
& bytearray
gets converted to integer.getstate()
- Returns object which captures current state of generatorsetstate(state)
- Sets state of generator for reproducibility. randoms_with_seed = []
## Below list will all numbers same because we are setting same seed everytime before generating random number.
for i in range(10):
random.seed(123)
randoms_with_seed.append(random.random())
print(randoms_with_seed)
print(random.random())
print()
print('Saving state and generating random numbers : ')
state = random.getstate() ## Getting state and saving it in random variable
print(random.random()) ## Generating random number
print(random.sample(range(10), k=3)) ## Selecting 3 random numbers form range(10)
print()
print('Generating random numbers again after setting previously saved state : ')
random.setstate(state) ## Setting state again
print(random.random()) ## Generating random number after setting previously saved state. It gives same random number as previous
print(random.sample(range(10), k=3)) ## Selecting 3 random numbers from range(10) after setting previously saved state. It gives same random numbers as previous
uniform(a,b)
- Returns floating point number N in range a <= N <= b
random.uniform(5,10)
triangular(low, high, mode)
- Returns random number between low
and high
with mode mode
random.triangular(5,10,3)
betavariate(alpha, beta)
- Beta distributionrandom.betavariate(5,10)
expovariate(lambd)
- Exponential Distribution.random.expovariate(0.1)
gammavariate(alpha,beta)
- Gamma distributionrandom.gammavariate(5,10)
gauss(mu, sigma)
- Gaussian distributionrandom.gauss(2,3)
lognormalvariate(mu,sigma)
- Log normal distributionrandom.lognormvariate(2,4)
normalvariate(mu,sigma)
- Normal distributionrandom.normalvariate(2,5)
vonmisesvariate(mu, kappa)
- random.vonmisesvariate(2,10)
paretovariate(alpha)
random.paretovariate(2)
weibullvariate(alpha,beta)
random.weibullvariate(2,10)
SystemRandom
- It's used to generate a random numbers using an underlying operating system. It uses os.urandom()
behind the scene.
rand = random.SystemRandom(123)
rand
rand.random()
When going through coding examples, it's quite common to have doubts and errors.
If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.
You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.
If you want to