Random Numbers
Throughout this chapter, to generate random numbers
[ 35 ]
we will work with the functions
provided by the numpy.random sublibrary:
In [ 1 ]: import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
%matplotlib inline
For example, the rand function returns random numbers from the open interval [0,1) in the
shape provided as a parameter to the function. The return object is an ndarray object:
In [ 2 ]: npr.rand( 10 )
Out[2]: array([ 0.40628966, 0.43098644, 0.9435419 , 0.26760198, 0.2729951 ,
0.67519064, 0.41349754, 0.3585647 , 0.07450132, 0.95130158])
In [ 3 ]: npr.rand( 5 , 5 )
Out[3]: array([[ 0.87263851, 0.8143348 , 0.34154499, 0.56695052, 0.60645041],
[ 0.39398181, 0.71671577, 0.63568321, 0.61652708, 0.93526172],
[ 0.12632038, 0.35793789, 0.04241014, 0.88085228, 0.54260211],
[ 0.14503456, 0.32939077, 0.28834351, 0.4050322 , 0.21120017],
[ 0.45345805, 0.29771411, 0.67157606, 0.73563706, 0.48003387]
])
Such numbers can be easily transformed to cover other intervals of the real line. For
instance, if you want to generate random numbers from the interval [a,b)=[5,10), you can
transform the returned numbers from rand as follows:
In [ 4 ]: a = 5.
b = 10.
npr.rand( 10 ) * (b - a) + a
Out[4]: array([ 7.27123881, 6.51309437, 7.51380629, 7.84258434, 7.62199611,
8.86229349, 6.78202851, 6.33248656, 8.10776244, 9.48668419])
This also works for multidimensional shapes due to NumPy broadcasting:
In [ 5 ]: npr.rand( 5 , 5 ) * (b - a) + a
Out[5]: array([[ 6.65649828, 6.51657569, 9.7912274 , 8.93721206, 6.66937996],
[ 8.97919481, 8.27547365, 5.00975386, 8.99797249, 6.05374605],
[ 7.50268777, 8.43810167, 9.33608096, 8.5513646 , 5.53651748],
[ 7.04179874, 6.98111966, 8.42677435, 6.22325043, 6.39226557],
[ 9.88334499, 7.59597546, 5.93724861, 5.39285822, 5.28435207]
])
Table 10-1 lists functions for generating simple random numbers.
[ 36 ]
Table 10-1. Functions for simple random number generation
Function Parameters Description
rand
d0, d1, ..., dn
Randoms in the given shape
randn
d0, d1, ..., dn
A sample (or samples) from the standard normal distribution
randint
low[, high, size]
Random integers from low (inclusive) to high (exclusive)
random_integers
low[, high, size]
Random integers between low and high, inclusive