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: