NumPy Random Module
Contents
NumPy Random Module#
The numpy.random
module provides us with random number generators (RNG). You can find the documentation here. As there name suggests, random number generators produce random numbers. In this section we highlight a few essential functions from the module:
np.random.random()
#
This function produces random floating point numbers from a uniform probability distribution function (PDF) on the interval \([0, 1)\) (\(1\) is excluded). If no arguments are provided a single number is generated:
np.random.random()
0.7036434202287197
If the length or shape is specified, random()
returns an array of random numbers:
np.random.random(5)
array([0.49111648, 0.98526062, 0.62609747, 0.65182162, 0.04046908])
np.random.random((2, 3))
array([[0.09456283, 0.93306441, 0.72075803],
[0.77853304, 0.03401744, 0.22719197]])
If you want to produce uniformly distributed random numbers \(R\) on the interval \([a, b)\), you can use random numbers \(r\) from the interval \([0, 1)\) by scaling and shifting them: $\( R = a + r*(b-a) \)$
For example, to generate uniform random numbers on the interval \([18, 30)\):
np.random.random(4)*(30 -18) + 18
array([29.73862401, 25.6986766 , 27.08709158, 24.01383967])
To read more about numpy.random.random()
, see the documentation.
np.random.randint()
#
This function produces random integers sampled from a uniform probability distribution on a specified interval.
The interval is defined by the first 2 arguments of randint()
, the end of the interval (second number) is not included in the interval:
#Random numbers from 1 up to 10
np.random.randint(1, 10)
4
Again, you can specify a size or shape of the output array:
np.random.randint(1, 10, 3)
array([3, 4, 3])
np.random.randint(1, 10, (2, 4))
array([[6, 8, 5, 1],
[3, 9, 9, 7]])
Random Numbers From Other Distributions#
numpy.random
provides us with many more RNG functions that sample from many of the most popular PDFs. You can see the full list in the documentation.
For example, the np.random.norm()
function produces random numbers sampled from the normal (Gaussian) distribution. Parameters like the mean and standard deviation (or first 2 moments) can be specified.
All of these functions can generate array outputs