Generating Random Numbers

January 20, 2018

Generating Random Numbers

NumPy’s random module provides a variety of useful functions that can generate random numbers.


Import Libraries

import numpy as np


Generating Random Numbers

rand returns random numbers from a uniform distribution over [0, 1), with 0 inclusive and 1 exclusive. The parameter allows us to control the size of the resultant array.

print(np.random.rand(5))
[0.85808936 0.91191128 0.04021352 0.46083434 0.48434375]


Generating Random Integers

randint returns random integers from a uniform distribution between [low, high), where low is inclusive and high exclusive.

If we only provide one parameter, low is assumed to be 0 and the input as high.

print(np.random.randint(5))
2


I generally prefer to include the parameter names to reduce ambiguity and increase the legibility of my code.

print('Generating a 5 by 2 array of integers, values ranging from 0 to 4, ends inclusive.\n')
print(np.random.randint(low=0, high=5, size=(5, 2)))
Generating a 5 by 2 array of integers, values ranging from 0 to 4, ends inclusive.

[[4 0]
 [2 0]
 [3 2]
 [1 2]
 [1 1]]
comments powered by Disqus