Get startedGet started for free

Generating random numbers using the np.random module

We will be hammering the np.random module for the rest of this course and its sequel. Actually, you will probably call methods of RNG instances more than any other function while wearing your hacker statistician hat. Let's start by taking a simple function, rng.random() for a test spin. The function returns a random number between zero and one. If you call rng.random() a few times, you should see numbers jumping around between zero and one.

In this exercise, we'll generate lots of random numbers between zero and one, and 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.

You may have noticed that, in the video, Justin generated 4 random numbers by passing the keyword argument size=4 to rng.random(). Such an approach is more efficient than a for loop: in this exercise, however, you will write a for loop to experience hacker statistics as the practice of repeating an experiment over and over again.

This exercise is part of the course

Statistical Thinking in Python (Part 1)

View Course

Exercise instructions

  • Instantiate and seed a random number generator, rng, using the seed 42.
  • Initialize an empty array, random_numbers, of 100,000 entries to store the random numbers. Make sure you use np.empty(100000) to do this.
  • Write a for loop to draw 100,000 random numbers using rng.random(), storing them in the random_numbers array. To do so, loop over range(100000).
  • Plot a histogram of random_numbers. It is not necessary to label the axes in this case because we are just checking the random number generator. Hit submit to show your plot.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Instantiate and seed the random number generator


# Initialize random numbers: random_numbers
random_numbers = ____

# Generate random numbers by looping over range(100000)
for i in ____:
    random_numbers[i] = ____

# Plot a histogram
_ = plt.hist(____)

# Show the plot
plt.show()
Edit and Run Code