Random and empty arrays

The random module of the NumPy package packs within it a whole range of functions for random sampling that perform operations right from creating a simple array of random numbers to drawing random samples from distribution functions.

The random.rand function generates random values from 0 to 1 (uniform distribution) to create an array of given shape:

# Creating a random array with 2 rows and 4 columns, from a uniform distribution
In [49]: np.random.rand(2, 4)
Out [49]:
array([[0.06573958, 0.32399347, 0.60926818, 0.99319404],
[0.46371691, 0.49197909, 0.93103333, 0.06937098]])

The random.randn function samples values from a standard normal distribution to build an array of given shape. If the shape parameter is not specified, a single value is returned as output:

# Creating a 2X4 array from a standard normal distribution
In [50]: np.random.randn(2, 4)
Out [50]:
array([[ 1.29319502, 0.55161748, 0.4660141 , -0.72012401],
[-0.64549002, 0.01922198, 0.04187487, 1.35950566]])

# Creating a 2X4 array from a normal distribution with mean 10 and standard deviation 5
In [51]: 5 * np.random.randn(2, 4) + 10
Out [51]:
array([[ 6.08538069, 12.10958845, 15.27372945, 15.9252008 ],
[13.34173712, 18.49388151, 10.19195856, 11.63874627]])

The random.randint function generates an array of integers between the specified lower and upper bounds, with the given shape. The limit excludes the upper bound. If the upper bound is not mentioned, it is considered to be 1 more than the lower bound defined:

# Creating an array of shape (2, 3) with random integers chosen from the interval [2, 5)
In [52]: np.random.randint(2, 5, (2, 3))
Out [52]:
array([[2, 4, 3],
[3, 4, 4]])

The empty function returns an array with arbitrary values for the given shape. This array requires no initialization and would perform faster than functions such as zeros and ones where the values have to be initialized. Caution is needed when using this function, and it is to be used only when it is certain that all the values in the array would be filled:

# Creating an uninitialized empty array of 4X3 dimensions
In [58]: np.empty([4,3])
Out [58]:
array([[0., 0., 0.],
[0., 0., 0.],
[1., 0., 0.],
[0., 1., 0.]])
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset