Numpy random numbers

Numpy provides strong support for random numbers. Here is the same example from the previous section.

>>> import numpy as np
>>> np.random.seed(123)
>>> np.random.random()
0.6964691855978616
>>> np.random.random()
0.28613933495037946
>>> np.random.random()
0.2268514535642031
>>> np.random.random()
0.5513147690828912
>>> np.random.random()
0.7194689697855631

This functionality is the same, except that we use the prefix np.random. The numbers are different because the random number generator is different.

Numpy provides array support, so, for example, you can generate a whole vector of random numbers - in this example, 10 of them:

>>> r = np.random.random(10)
>>> print(r)
[ 0.42310646  0.9807642   0.68482974  0.4809319   0.39211752  0.34317802
  0.72904971  0.43857224  0.0596779   0.39804426]

You can do the coin toss experiment as we did in the previous section using the numpy where function:

>>> r = np.random.random(10)
[ 0.42310646  0.9807642   0.68482974  0.4809319   0.39211752  0.34317802
  0.72904971  0.43857224  0.0596779   0.39804426]
>>> coin = np.where(r < 0.5, "H", "T")
>>> print(coin)
['H' 'T' 'T' 'H' 'H' 'H' 'T' 'H' 'H' 'H']

The where function creates a new array with either H or T depending on whether the corresponding component of r is less than or greater than 0.5.