Random Number Generator Using Numpy

Numpy’s random module, a suite of functions based on pseudorandom number generation. Random means something that can not be predicted logically.


In this example, we will stimulate a coin flip. We will use the function np.random(), which draws a number between 0 & 1 such that all numbers in this interval are equally likely to occur.

If the number we draw is less than 0.5, which has a 50% chance of happening, we say heads & tails otherwise. This type of result where results are either True (Heads) or False (Tails) is referred to as Bernoulli trial.

The pseudorandom number works by starting with an integer called a seed & then generates numbers in succession. The same seed gives the same sequence of random numbers, hence the name “pseudo” random number generation. If we want to have reproducible code, it is good to seed the random number generator using the function.

To do the coin flips, we import , seed the random number generator, & then draw four random numbers. We can specify how many random numbers we want with the keyword.

The first number we get is less than 0.5, so it is heads while the remaining three are tails. We can show this explicitly using the less than operation, which gives us an array with boolean values, True for heads while False for tails.

Finally, we can compute the number of heads by summing the array of booleans , because in numerical context, Python treats True as one & False as zero.

Simulating Four Random Coin Flips

In the following example, we want to know the probability of getting four heads if we were to repeat the four flips of the coin over & over again. We can do this with a for loop.

We first initialize the count to zero. We then do repeat 10,000 repeats of the four-flip trials. If a given trial had four heads, we would increase the count.

So what is the probability of getting all four heads? It’s the number of times we got all heads, divided by the total number of trials. The result is about 0.06.

Example of Generating Random Numbers

In this example, we’ll generate lots of random numbers between zero & one, & then plot a histogram of the results. If the numbers are truly random, all bars in the histogram should be of (close to) equal height.

For this example we will need to:

  • Seed the random number generator with using the seed .
  • Initialize an empty array, random_numbers, of 100,000 entries to store the . Make sure we use to do this.
  • Write a loop to draw 100,000 random numbers using , storing them in the array. To do so, loop over .
  • Plot a histogram of . It is not necessary to label the axes in this case because we are just checking the random number generator.

When we run the above code, it produces the following result:


Data Scientist & Machine Learning Engineer