Lesson 12: Loops and Simulations
In this lesson, students gain more practice using while loops as they develop a simulation that repeatedly flips coins until certain conditions are met. The lesson begins with an unplugged activity in which students flip a coin until they get 5 heads in total, and then again until they get 3 heads in a row. They will then compete to predict the highest outcome in the class for each statistic. This activity motivates the programming component of the lesson in which students develop a program that allows them to simulate this experiment for higher numbers of heads and longer streaks.
The ability to model and simulate real-world phenomena on a computer has changed countless fields. Researchers use simulations to predict the weather, the stock market, or the next viral outbreak. Scientists from all disciplines increasingly rely on computer simulation, rather than real-life experiments, to rapidly test their hypotheses in simulated environments. Programmers might simulate users moving across their sites to ensure they can handle spikes in traffic, and of course videogame and virtual reality technology is built around the ability to simulate some aspects of the real world. The speed and scale at which simulations allow ideas to be tested and refined has had far-reaching impact, and it will only continue to grow in importance as computing power and computational models improve.
Getting Started (10 Minutes)
Activity (60 Minutes)
Wrap-up (5 Minutes)
Students will be able to:
- Use a while loop in a program to repeatedly call a block of code.
- Use variables, iteration, and conditional logic within a loop to record the results of a repeated process.
- Identify instances where a simulation might be useful to learn more about real-world phenomena.
- Develop a simulation of a simple real-world phenomenon.
- Print a Worksheet - Flipping Coins for each student.
- A coin for every student or pair of students.
For the Students
- Models and Simulations - a program which replicates or mimics key features of a real world event in order to investigate its behavior without the cost, time, or danger of running an experiment in real life.
Getting Started (10 Minutes)
Coin Flipping Experiment
Flip a coin until you get 5 total heads. Then again until you get 3 heads in a row. Record your results and predict the highest result in the class.
Run a simple experiment by hand that it would be unmanageable to run on a larger scale, thus motivating the need to simulate it on a computer.
Distribute: Worksheet - Flipping Coins and give each student / pair of students a coin.
"We’re going to run two simple experiments. Use your worksheets to keep track of your results (by writing “H” or “T” for each flip) but keep them a secret for now."
Experiment 1: Groups will flip their coins as many times as it takes in order to get 5 heads total
- Experiment 2: Groups will flip their coins as many times as it takes to get 3 heads in a row
- "Let’s have a little competition. You should have recorded your results for your two experiments. Based on your experiment, predict, among every group in the class the most and fewest flips needed to complete each of the experiments."
Collect worksheets (or just have students share answers) to determine how accurate guesses were. Perhaps offer small prizes for the group whose guesses were most accurate.
That was pretty interesting with only 5 total heads or a streak of 3 heads. If we want to run this experiments for higher numbers of heads or longer streaks of heads however, we’ll quickly find that it’s tedious to do once, let alone many times. Luckily we know now that we can use loops to repeatedly perform commands, so we’re going to simulate these larger experiments instead.
Activity (60 Minutes)
App Lab: Loops and Simulations
- Develop a simulation in App Lab that allows you conduct the experiments from the warm-up with many more coins.
- Repeat the warm-up activity using the simulation and update hypotheses as a result.
Wrap-up (5 Minutes)
"Update your hypothesis based on the results of your simulation and predict the outcomes of an even larger experiment using the new knowledge you have gained."
On the second part of their worksheets, students are asked to extend their hypotheses to try to predict how long it might take to flip 10,000,000 heads or find a streak of 20 heads. Even for a computer, these could take a great deal of time to run, but luckily students should have developed intuitions about these problems based on their earlier simulations.
Their actual predictions are less important than whether they demonstrate having reflected on the outcomes of the earlier simulation.
- Once students have finished writing their predictions for these problems, they should present their predictions and their reasons for making them with their classmates.
- Discuss whether and how the results of their earlier simulation impacted their new hypotheses.
Not all problems are as easy to simulate as a coin flip of course, and we’ve even seen how some problems we can simulate still take a very long time to run.
Simulations are an increasingly important tool for a variety of disciplines. Weather and traffic predictions are based on computer models that simulate weather patterns or people moving through a city. Scientific research, whether in physics, chemistry, or biology, increasingly uses simulations to develop new hypotheses and test ideas before spending the time and money to run a live experiment.
Before you use most of your favorite websites and apps, they will be tested by simulating high levels of traffic moving across the server. Simulations take advantage of computers’ amazing speed and ability to run repeated tasks, as we’ve seen through our exploration of the while loop, in order to help us learn more about the world around us.
As computers get ever faster and models improve, we are able to answer old questions more quickly and start asking new ones.
- Extend this activity to new statistics, rolling dice, etc. Use these both as opportunities to practice programming and to develop the habit of using simulations to refine hypotheses.
- How long does it take for the number of heads and tails flipped to be equal?
- Longest streak where each roll is greater than or equal to the last
- Longest streak made of only five (any five) of the six faces on the die (i.e., not equal to the other)
The series of problems and tasks in this lesson progressively build up a series of experiments that simulate coin flipping.
We ask students to make a hypothesis, then experiment with code, revise the hypothesis and so on, around some question. Below are some guidelines about what students should find.
Insights: The following insights should arise from this experiment:
Total Heads: When trying to flip 5 heads, it is quite possible that it will only take 5 flips, but it may also easily take 15 or 20. Relative to the number of heads you are looking for, this is a massive range! When you are trying to flip 10,000 heads the likely range is typically between 19,000 and 21,000, and typically much closer. As you are looking for more flips, the relative width of the likely window shrinks.
Longest Streak: When trying to find a streak of 3 heads it will typically take between 3 (it’s always possible!) and 20 flips, though of course it may take longer. Even slightly longer streaks of heads, however, will rapidly increase the average time it takes to find that streak. Looking for a streak of 12 heads might occasionally happen in fewer than 100 flips, but it can also easily take tens of thousands. As the length of the streak increases, the number of flips it takes to find that streak grows rapidly.
How Much Math is Necessary?
This lesson might seem to naturally lend itself to a more detailed discussion of the mathematical properties of random experiments. Flipping coins is, after all, perhaps the most classic example of a random experiment.
The goal of this lesson is not for students to walk away knowing the precise mathematical relationship between the number of coins flipped and the number of heads observed or the longest streak of heads. Instead they are supposed to appreciate that questions that might be impossible or hard to address by hand are possible to examine by using computer simulation. Just as developing a mathematical model is one way to address a problem, so too is developing a simulation.
There’s no need to dive deep into the mathematics this lesson touches on, but students should be able to describe the patterns they observed while running their simulations, and use those observations to justify new hypotheses.
- Make a Hypothesis
- (click tabs to see student view)
Pause Point - Make a Hypothesis
- Use this level to describe the fact that students will be making a simulation of flipping coins.
- Ask them to make a prediction for the outcomes of the experiments they will run.
Make sure students make this prediction before moving on.
- Students should record their predictions in the space provided on their worksheets.
Make a Hypothesis
Over the next several exercises we are going to be building a program that simulates flipping coins in order to find out how many flips it takes to get 10,000 heads in total and how many flips it takes to get a streak of 12 heads in a row. If you're following along on the worksheet, you might have already tried these experiments at a smaller scale, flipping a coin until you got 5 total heads and a streak of 3 heads in a row. Doing this smaller scale activity may have given you some intuition for what the outcome of the larger experiment will be, but before running an experiment it's usually a good idea to develop a hypothesis.
What will be the maximum and minimum number of flips it will take to get 10,000 heads? When trying to get 5 heads some groups may have taken exactly 5 flips while others took 15 or more (3 times the number of heads you were looking for!). Do you think this wide range of values will persist when looking for 10,000 heads?
What will be the maximum and minimum number of flips it will take to get a streak of 12 heads? Again think about the patterns you've observed. If you need 4 times as many heads in a row will it take 4 times as long? Try to justify the values you choose.
Write down your predictions on the worksheet so you can reference them later.
It's not important whether you're right (you'll have the answer soon enough anyway!) but it will let you reflect on your thinking. In fact, you might even get some new ideas you'd like to investigate as a result!
To start, we're going to simulate flipping a coin 10 times. You might be thinking that isn't many coin flips, and that we could just do those flips in real life, but this is actually an important step in developing a simulation. At small scales we can make sure our code is working as intended because we can still visually confirm its output. Once we're convinced that the logic of our program is reliable we'll move up to simulating larger numbers of flips.
The core logic of our program will be focused on a
while loop that simulates flipping a coin by repeatedly generating random 0's or 1's using
randomNumber. This is a great opportunity to keep practicing using loops while applying your knowledge of variables, iteration, and
- When we want to flip a coin with a computer we will instead generate a random number between 0 and 1.
- Write a program that uses a
whileloop to flip a coin 10 times and writes the value of each flip to the screen. The example below shows how your program should run.
- HINT: you will need to use a counter variable in your
whileloop to keep track of how many times the coin has been flipped.
Let's say that a 1 is a heads. If we want our simulation to run until we reach a certain number of heads then we will need a way to count the number of heads that have been flipped. In order to do this you will need to add a variable that acts as a counter. Initialize it to 0, and every time you flip a heads (1) increment your counter by 1. At the end of your program you should write the value to the screen.
- Add a variable that counts the number of heads (1's) and write its value to the screen after each flip.
- Run your program severals times and validate that the number of heads recorded is correct by visually checking the flips you've printed to the screen.
- Hint: you will also need to store your current coin flip in a variable to complete this challenge.
Changing the Loop Condition
Currently our loop condition is based on a counter variable that keeps track of the total number of flips, but our simulation should only run while we have fewer than the target number of heads. In this exercise you are going to change the condition used by your
while loop so that your simulation terminates once you have flipped 5 total heads. At the end of the loop we will write the total number of flips to know how many flips it took to get 5 heads.
- Change the looping condition to use the variable you are using to keep track of the number of heads. Your loop should run as long as you have fewer than 5 total heads.
- Add code after your loop that writes the total number of flips.
- Test your program several times to make sure it works as expected. See the example below.
- Note: the simulation is always terminating once it flips its 5th heads. Sometimes this means the text output runs off the screen. We will address this in the next exercise.
You're ready to increase the number of heads your simulation is looking for and test your first hypothesis. Before we move up to the full 10,000 heads, however, we're going to perform a quick check of our program logic. When you make changes to your program it is possible that some portion of your programming logic will stop working as you expected. In order to feel more confident about your model you will first change the number of heads you are looking for to a number that we can still visually verify (7 heads). If our code still works after making changes then we should be confident that it should work at 10,000. We will remove the intermediate output and run the full simulation!
- Increase the number of heads you are looking for to 7 and visually confirm that the code is still working as you expect.
- If everything seems to be working, comment out the
writecommand that displays the results of each flip. You can use
to comment out a single line of code. Make sure that the total count of flips still prints though!
- Run your simulation and find out how long it takes to get to 10,000 heads. Then run it a few more times. What patterns are you noticing? Record your results and move on.
- Update your Hypothesis - Part 1
- (click tabs to see student view)
Updating Your Hypotheses
If everything has gone well you should already be able to make a determination about your first hypothesis.
- How close were your guesses on the high and low bounds for the number of flips to get 10,000 heads?
- Were you at all surprised by this result? If they were different from what you predicted why might this be the case?
Take some time to write out your thoughts and whether your understanding of this system has changed. Update either of your hypotheses to reflect what you observed in this first experiment.
Streaks of Heads
We are going to alter our simulation so that it doesn't count the total number of heads, but rather the longest streaks of heads. This will allow us to simulate how many flips it takes to get 12 heads in a row.
To begin with you will change your looping condition so that the loop again only runs 10 times. This will allow us to visually confirm our code is working.
Keeping Track of Streaks: We know we need to count streaks of heads, how do we do this in code? Do we need to keep track of all the previous flips so we know that we're on a streak?
The answer is: no. We can instead just count in a clever way that makes our code pretty simple. Make a variable to use as a counter and...
- every time you see heads, add 1 to a counter.
- every time you see tails, set the counter back to 0.
Here is some psuedocode showing how it works. You might take a minute to study and reason about why and how it works.
// Ouside loop headsCount <-- 0 // Inside loop IF (current flip is a heads) headsCount <-- headsCount + 1 ELSE headsCount <-- 0 DISPLAY (current flip) DISPLAY (headsCount)
- Change your
whileloop's condition so that it only runs 10 times.
- The example below shows an example of what output from your program might look like.
Changing the Loop Condition: Streaks of Heads
We want our simulation to run while the streak of heads is less than a target length. In order to do this we'll need to change our looping condition to use the variables we've been using to count our streak of heads. To begin with your simulation should look for a streak of 3 heads so that you can still visually confirm the output.
- Change the condition used by your
whileloop so that it now runs while the streak of heads is less than 3.
- Test your program by running it and visually confirming that its output is correct. It should run like in the example below.
- Note: As before it's possible that your output will sometimes run off the screen. You can still confirm your code is working as you intend (it should never run after a streak of 3) and we will address this issue in the next exercise.
Streaks of Heads: 12 in a Row
We're almost ready to test our second hypothesis and find out how long it takes to get 12 heads in a row. Just as before we're first going to visually test our code with a different length streak (4) before removing most of the visual output and running the code for a streak of 12.
- Change your simulation to run until you get a streak of 4 and visually verify that the values calculated are accurate.
- Comment out the lines of code that write the current coin flip and the current streak count. You can use
to comment out a single line of code.
- Change your simulation to run until you get a streak of 12 heads.
- Run your simulation a few times and record your results!
- Update your Hypothesis - Part 2
- (click tabs to see student view)
Updating Your Hypotheses - Part 2
You should now be ready to compare the results of your simulation to your second hypothesis.
- How accurate was your prediction of the upper and lower bounds for the number of flips to get a streak of 12 heads?
- Were you at all surprised by this result? What might explain the differences between your prediction and what you observed?
Just as before, you should update your hypotheses to reflect the results of your simulation. Try to come up with a reasonable explanation for the results you observed.
- Experiment With Simulation
- (click tabs to see student view)
Your simulation can be updated or changed however you like. What new questions do you have? Do you want to look for longer streaks of heads? Do you want to roll a die instead of flipping a coin? Make any changes and improvements to your simulation that you like.
Computer Science Principles
2.3 - Models and simulations use abstraction to generate new understanding and knowledge.
2.3.1 - Use models and simulations to represent phenomena. [P3]
- 2.3.1A - Models and simulations are simplified representations of more complex objects or phenomena.
- 2.3.1C - Models often omit unnecessary features of the objects or phenomena that are being modeled.
- 2.3.1D - Simulations mimic real world events without the cost or danger of building and testing the phenomena in the real world.
2.3.2 - Use models and simulations to formulate, refine, and test hypotheses. [P3]
- 2.3.2A - Models and simulations facilitate the formulation and refinement of hypotheses related to the objects or phenomena under consideration.
- 2.3.2B - Hypotheses are formulated to explain the objects or phenomena being modeled.
- 2.3.2D - The results of simulations may generate new knowledge and new hypotheses related to the phenomena being modeled.
- 2.3.2E - Simulations allow hypotheses to be tested without the constraints of the real world.
- 2.3.2F - Simulations can facilitate extensive and rapid testing of models.
- 2.3.2G - The time required for simulations is impacted by the level of detail and quality of the models, and the software and hardware used for the simulation.
- 2.3.2H - Rapid and extensive testing allows models to be changed to accurately reflect the objects or phenomena being modeled.
4.1 - Algorithms are precise sequences of instructions for processes that can be executed by a computer and are implemented using programming languages.
4.1.2 - Express an algorithm in a language. [P5]
- 4.1.2A - Languages for algorithms include natural language, pseudocode, and visual and textual programming languages.
- 4.1.2B - Natural language and pseudocode describe algorithms so that humans can understand them.
5.1 - Programs can be developed for creative expression, to satisfy personal curiosity, to create new knowledge, or to solve problems (to help people, organizations, or society).
5.1.1 - Develop a program for creative expression, to satisfy personal curiosity, or to create new knowledge. [P2]
- 5.1.1A - Programs are developed and used in a variety of ways by a wide range of people depending on the goals of the programmer.
CSTA K-12 Computer Science Standards (2017)
AP - Algorithms & Programming
- 3A-AP-15 - Justify the selection of specific control structures when tradeoffs involve implementation, readability, and program performance and explain the benefits and drawbacks of choices made.
DA - Data & Analysis
- 2-DA-09 - Refine computational models based on the data they have generated.