Lesson goal: Making a histogram with arrays

Previous: Arrays and recurrence relations | Home | Next: Histogram Pi's digits

A histogram is a very useful construct. It is a chart for displaying how frequent a given quantity might appear in an otherwise "random" stream of data. It usually involves bars that are drawn in proportion to how frequent a given number occurs. Histograms are very useful for exposing patterns in a stream of numbers.

Arrays are the perfect data type for creating histograms. In this lesson, we'll again analyze the "randomness" of our random number generator, but we'll make a histogram in the process.

Below is some code that will declare a histogram called hist and initally set the elements from -100 to 100 of it equal to zero. Next, using the for c=1,10000 do loop, we'll ask the computer to throw 10,000 random numbers. We'll choose each random number to exists, in variable i, between -100 and 100, the same as the bounds of our histogram, hist. With each random number in variable i, we'll create a histogram by incrementing the $i^{th}$ element of array hist with each random number.

The last for loop will make a simple plot of the histogram by drawing a line for each "bar" of the histogram. By looking at the histogram plot, what can you conclude about the random number generator?

Now you try. Fix the line right after the i = math.random(...) line to add one count to the $i^{th}$ element of the histogram stored in the array called hist.

Type your code here:


See your results here:

This code will not run! You have to fix the line right after the i = math.random(-100,100) line to do this:
  • Realize that i now contains a random numnber between -100 and 100.
  • We are trying to count and log the number of occurrences of these random numbers.
  • To track how many times the random number in variable i occurs, we want to increment the $i^{th}$ element of array hist.
  • Doing these increments creates a histogram of the random number occurrences.
  • So in the line following the i = math.random(...) line, how will you add one to the current count in histogram element hist[i] ?
Dismiss.
Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.