numpy.random — Generating Random Numbers In Python

Om Rastogi
Analytics Vidhya
Published in
2 min readJun 8, 2020

--

Random number have lots of application like, cryptography, game and Neural Network. Here we’ll discuss and identify different methods for generating random numbers in NumPy module in python.


import numpy as np

numpy.random.random (size)— Return random floats in the half-open interval [0.0, 1.0), ie 1.0>x≥0.0

>>>np.random.random((2,2))array([[ 0.66032591,  0.91397527],
[ 0.63366556, 0.36594058]])

numpy.random.randint(low, high, size, dtype=int) — Return random integers from low to high from the “discrete uniform” distribution.

>>> np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)array([[ 8,  6,  9,  7], 
[ 1, 16, 9, 12]], dtype=uint8)

numpy.random.randn(d1,d2,..dn) — Return a sample/s from the “standard normal” distribution, for given dimension.

>>> np.random.randn(2,2)array([[ 0.6762164 , -1.37066901],
[ 0.23856319, 0.61407709]])

numpy.random.rand(s1,s2,..sn) — Random values in a given given dimension and ranges between (0,1).

>>> np.random.rand(3,2)
array([[ 0.14022471, 0.96360618],
[ 0.37601032, 0.25528411],
[ 0.49313049, 0.94909878]])

random.rand and random.randn are similar function, both in functionality and syntax and can be confused easily.
random.rand — Returns sample according to standard normal distribution.
random.randn
— Returns numbers ranging between (0,1)

numpy.random.normal(loc=0.0, scale=1.0, size=None) Draw random samples from a normal (Gaussian) distribution.

loc : Mean (“centre”) of the distribution
scale : spread or “width” of the distribution
>>> np.random.normal(3, 2.5, size=(2, 4))
array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677],
[ 0.39924804, 4.68456316, 4.99394529, 4.84057254]])

These are the most methods used for creating random number. More details can be searched in documentation. To get broader knowledge on numpy check my article.

If this article was helpful, check my other articles on similar topics.

--

--

Om Rastogi
Analytics Vidhya

I believe in an altruistic world, where creativity and imagination replace repetitive work