Share @ Google LinkedIn Facebook  random-numbers, distributions

Overview

Python random module provided implementations of generating pseudo-random numbers for various distribution.

It provides functions to generate below distributions:

  • Uniform
  • Normal (Gaussian)
  • lognormal
  • negative exponential
  • gamma
  • beta

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 puspose, please use secrets module.

In [1]:
import random
import matplotlib.pyplot as plt
%matplotlib inline
random.random() ## random() generates random floating number in range [0,1.0)
Out[1]:
0.78580578011011

Basic functions to work with random numbers:

  • randint(a,b) - Generates random integer in range a <= integer<=b
  • randrandge(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.
In [2]:
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))
8
3
7
3
4
[11, 0, 2, 11, 10]
Before shuffling x : [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
After shuffling x : [10, 15, 45, 35, 50, 5, 40, 25, 20, 30]
[45, 35, 20, 15, 10]
[3, 4]
848

Below are list of functions which can be used to generate same results using random numbers. It can help different users to reproduce same results in research.

  • seed(a=None, version=2) - This function initializes random number geneator with seed so that it produces same result which can be used for reproducing results.
    • If 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 generator
  • setstate(state) - Sets state of generator for reproducibility.
In [3]:
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
[0.052363598850944326, 0.052363598850944326, 0.052363598850944326, 0.052363598850944326, 0.052363598850944326, 0.052363598850944326, 0.052363598850944326, 0.052363598850944326, 0.052363598850944326, 0.052363598850944326]
0.08718667752263232

Saving state and generating random numbers :
0.4072417636703983
[1, 0, 6]

Generating random numbers again after setting previously saved state :
0.4072417636703983
[1, 0, 6]

Various Distributions:

  • uniform(a,b) - Returns floating point number N in range a <= N <= b
In [4]:
random.uniform(5,10)
Out[4]:
7.681010200169634
  • triangular(low, high, mode) - Returns random number between low and high with mode mode
In [5]:
random.triangular(5,10,3)
Out[5]:
5.165428607191616
  • betavariate(alpha, beta) - Beta distribution
In [6]:
random.betavariate(5,10)
Out[6]:
0.2974248166980243
  • expovariate(lambd) - Exponential Distribution.
In [7]:
random.expovariate(0.1)
Out[7]:
9.103073294022408
  • gammavariate(alpha,beta) - Gamma distribution
In [8]:
random.gammavariate(5,10)
Out[8]:
21.097672235666323
  • gauss(mu, sigma) - Gaussian distribution
In [9]:
random.gauss(2,3)
Out[9]:
-4.174579686127806
  • lognormalvariate(mu,sigma) - Log normal distribution
In [10]:
random.lognormvariate(2,4)
Out[10]:
5506.711742345207
  • normalvariate(mu,sigma) - Normal distribution
In [11]:
random.normalvariate(2,5)
Out[11]:
-10.413396735122875
  • vonmisesvariate(mu, kappa) -
In [12]:
random.vonmisesvariate(2,10)
Out[12]:
2.4408789925446333
  • paretovariate(alpha)
In [13]:
random.paretovariate(2)
Out[13]:
1.2084763354003478
  • weibullvariate(alpha,beta)
In [14]:
random.weibullvariate(2,10)
Out[14]:
1.8689912243565223

SystemRandom - It's used to generate random number using underlying operating system. It uses os.urandom() behind the scene.

In [15]:
rand = random.SystemRandom(123)
rand
Out[15]:
<random.SystemRandom at 0x5573bb0f8178>
In [16]:
rand.random()
Out[16]:
0.062253476957529696

Let other learners know about this article @ Google LinkedIn Facebook
Sunny Solanki  Sunny Solanki