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:

What happens if you divide $x$ by some number in the n= line? Think: a bell shaped curved has two parameters, the average and standard deviation. Can you see and manipulate both in this lesson? 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.