Random numbers generation with numpy


Numpy’s random number routines produce pseudo random numbers using combinations of a 

1. BitGenerator to create sequences and a 
2. Generator to use those sequences to sample from different statistical distributions

BitGenerators actually provide a stream of random bits based on different algorithms. Thus they generate random numbers which are typically unsigned integer words filled with sequences of either 32 or 64 random bits.

Generators are objects that transform sequences of random bits from a BitGenerator into sequences of numbers that follow a specific probability distribution (such as uniform, Normal or Binomial) within a specified interval.



Example BitGenerators are

1. PCG64 : This is the BitGenerator for the PCG-64 pseudo-random number generator. PCG stands for Permuted Congruential Generator and is a 128-bit implementation of O’Neill’s permutation congruential generator.

2. MT19937 : This BitGenerator is container for the Mersenne Twister pseudo-random number generator.


Now, we can use any BitGenerator we like. We can create an instance of that BitGenerator and pass the instance to the Generator.
NOTE : However, PCG64 has better statistical properties than the legacy MT19937. PCG is said to be a family of simple, fast, space-efficient and statistically good algorithms for Random Number Generation.

The default BitGenerator used by Generator is PCG64.

Now, let us try the concept in a few lines of Python code.


from numpy.random import Generator, PCG64

# pass an instance of PCG64 to Generator
rng = Generator(PCG64())

# Simple Random data
# return random floats in the half-open interval [0.0, 1.0).
x = rng.random()

print(x)

# Distribution
# number of trials, probability of each trial

n, p = 10, .5
y = rng.binomial(n, p, 1000)

print(y)



But remember, I already mentioned that the default BitGenerator used by Generator is PCG64. That is, Python provides a method called default_rng(), which constructs a new Generator with the default BitGenerator (PCG64).

So, we should write,

from numpy.random import default_rng

# It construct a new Generator with the default BitGenerator (PCG64). 
# returns the initialized generator object.
# default_rng() is the recommended constructor for Generator.

rng = default_rng() # instead of Generator(PCG64())

y = rng.random()

print(y)






Comments

Popular Posts