Lesson goal: Checking random numbers

Previous: Divisibilty tester (2) | Home | Next: Graphing inequalities (x-axis)

As disussed in this lesson, math.random can be used to find a random number. Like cards in gambling, should we wonder if the computer's random number generator is "fair?" That is, are all numbers within the random range we select equally likely to appear?

The theory is this: if we choose random numbers between 1 and 10, and we do this 100 times. We'd generally expect each number (1,2,3,4,5,6,7,8,9 and 10) to come up 1/10th of the time, or we'd expect to see each number come up 10 times in the 100 choices. This sounds fair, right?

Let's test this theory here using a for-loop, if-statement, and the == operator. Let's see if math.random is "fair." If you ask for $N$ random numbers, and there are $m$ possible numbers, then you'd expect each number to come up $M/m$ times. So asking for $N=100$ random numbers between $1$ and $10$, each number should come up $100/10=10$ times. Confused? Think of a die. Roll it 100 times, you'd expect each number to come up $100/6=16.6$; we'd expect each number to appear about 16 times.

Now you try. After fixing the code, click the "run" button a few times and see if your target number comes up about total/10 times. The larger you make total, the better your answer should be.

Type your code here:

See your results here:

The code here will not run. Fill in the number of random numbers to draw in the N= line. Next, choose a number between 1 and 10 that you want to watch for. Fill this into the target= line.

Now for the if statement. If rn is the random number (between 1 and 10) and target is the number you wish to track, what should the if statement true/false question be? Note the body of the if statement increases a variable called count by 1. Meaning "if my number comes up, keep track of it by counting up one each time." 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.