2.5 A first pass

Download notebook Interact

Remember the three girls in a family problem?

Now we have variables and functions, we can do a first pass at solving the problem.

First we import the function we need to make random numbers. Don’t worry about this line for now:

# Fetch the "randint" function from the Numpy library.
from numpy.random import randint

This function can give us random numbers from 0 up to, but not including 2, like this:

# Generate a random number that is either 0 or 1
randint(0, 2)
1

You can run the same cell over and over by pressing Control and Enter together (Control - Enter). This is like Shift - Enter, except Control - Enter leaves the focus inside the cell, so you can run the same again immediately.

We take 1 to mean a girl, and 0 to mean a boy.

Now we have variables, we can do better than running this cell four times, and counting the number of time we see 1.

# Get four random numbers between 0 and 1.
a = randint(0, 2)
b = randint(0, 2)
c = randint(0, 2)
d = randint(0, 2)
# Count the number of ones by adding them up.  Show the result.
a + b + c + d
1

Using Control - Enter, run this cell 100 times. Count the number of times you see the result 3. Divide that number by 100, and you have an estimate of the number of families with four children that have exactly three girls.

Still, it’s boring to have to run that cell 100 times. We might also like the computer to execute these steps many more times - say - 10000 times. We will need to do some more programming to tell the computer how to do this.