Lesson goal: Histogramming Random Numbers

Previous: Histogramming uniform rnd nums | Home | Next: Cellular Automatum

We've discussed generating uniform random numbers in a past lesson. In this lesson, we'll look at how to generate "normally distributed random numbers," or random numbers that follow the "bell shaped" or "normal" distribution.

Believe it or not, generating normally distributed numbers works like this. First, you select two uniformly distributed numbers $u$ and $v$. These can be found from a call to math.random() as usual. Next, compute $x$ from: $$x=\sqrt{-2\ln u}\sin(2\pi v).$$ The $x$'s that this formula produces will be random numbers that are normally distributed. They will have an average of $0$ and a standard deviation of $1$. This is called the "Box-Muller" transformation. In the code below, the numbers are computed in the x= line. To prepare it for histogramming, we'll compute n in the next line which will be $n=20(x+2.5)$. By adding $2.5$ to $x$, we shift the average to 2.5, then multiply by $20$ to scale it nicely to our histogram. Feel free to change these numbers.

As for your programming goals, this is another use of arrays, storing numbers then analyzing them by doing through the array with a for-loop. As for math, a look at histograms and a quirky way of converting uniform random numbers to normally distributed random numbers. Cool!

Now you try. Try running the code as is, then tweaking the $2.5$ and the $20$. Compare and contrast this histogram with the one produced here

Type your code here:

See your results here: