Course 2.2Lesson 5 of 5
In this project we build a dice laboratory. The program rolls a die 600 times with a seed so that the result is the same each run, counts each face with a dictionary, compares each count with the expected 100, finds the mean, the mode and the biggest gap from the expected count, and draws a bar chart in text. We plan what a fair die should show, build the program in steps with the random and statistics modules, test it with different seeds and different numbers of rolls, and extend it with two dice and the sum of two dice.
Try the code and the simulations beside the lesson.
After this lesson you can
random and statistics together in one program,Is a die fair? A fair die gives each face with the same chance, 1 in 6. If you roll it 600 times, you expect about 100 of each face. But "about" is the interesting word. Will it be exactly 100? Close to it? How close? You can find out in seconds, by rolling a virtual die 600 times.
Before we run any code, think.
A laboratory is for experiments. Try these, and write down what you expect before each.
| Experiment | What do you expect? |
|---|---|
| a different seed | different counts, still close to 100 each |
| 60 rolls instead of 600 | counts near 10, but the gaps are bigger in proportion |
| 60 000 rolls | each count very close to 10 000 in proportion |
a loaded die, with random.choice([1, 2, 3, 4, 5, 6, 6, 6]) | face 6 comes about three times in eight |
The last two rows show the law of large numbers: the more trials, the closer the share of each face gets to the expected 1 in 6. The count can still wobble by a hundred or two, but as a share of the total it becomes tiny. This is the idea behind every poll and every simulation.
The bars are what to expect. Your random counts will wobble around them, and wobble less, in proportion, the more you roll.
Pick one or two, and do them without looking at a solution. Write down what you expect first.
datetime.statistics.pstdev on the six counts. Is it small?range(1, 6). A die has six faces, and randint(1, 6) is the right call.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.