Chapter 4.5 - Coin Flip Simulation

Time Estimate: 45 minutes

4.5.1. Introduction and Goals

Coin Flip is an app that simulates the flipping of a two-sided coin. This app uses Thunkable’s random number generator and two images to simulate the coin flip.

Objectives: In this lesson, you will learn to:

  • create an artifact that uses Randomness and simulates a model;

  • create a simple model of a coin flipping;

  • use random number blocks to generate a random value in a specific range;

  • define a global variable and assign it an initial value;

  • use a conditional statement, IF/Else, to evaluate a variable and follow an algorithm based on the value of a variable;

  • use a loop to repeat the coin flip many times and calculate the percentage of heads.

Getting Ready

Open a new project in Thunkablearrow-up-right. Use the Drag and Drop interface to create the app.

You will need to find two images of a coin for heads and tails, or use the files provided here:

The Coin Flip User Interface

The UI for the first version of our Coin Flip app will consist of two UI Components: a Button and an Image. The Button is used to flip the coin to either heads or tails. The Image is used to display either heads or tails when the coin is flipped.

Coding the Behavior

The Coin Flip app should simulate flipping of a two-sided coin. When the user clicks the button, the coin should be flipped and land on either heads or tails. The picture should change to represent the side teh coin lands on. A variable coin will be uwesd to represent either heads or tails, and an If/Else statement will be used to display the correct image.

Handling the Button Click Event

Nearly all of the app’s code will be inside the When Button Click handler. Begin by dragging the When Button Click handler from the Toolbox onto the Blocks workspace.

Coin Variable

How should we represent the coin that is being flipped? The answer, of course, is that we will use an app variable.

Coin will be an app variable that can have one of two values: 1 (for heads) or 2 (for tails). First, initialize the variable by getting an initialize app variable block from the Toolbox. Name the variable coin and set coin to heads by giving it an initial value of 1. Now, each time Button1 is clicked, coin should ‘flip’ and randomly ‘land’ on 1 (heads) or 2 (tails). To do this, you will need to get a setter block for coin from the Toolbox.

Simulating the Coin Flip

To randomly set the value of a coin to be either 1 or 2, you will need to use Thunkable’s random integer block. Thunkable has several blocks for randomness in the Toolbox’s Math drawer. You may have already seen and used these blocks.

  1. Random fraction: Randomly selects a number (such as 0.532) between 0 and 1 (not including 1:

4.4RandomFractionBlock.PNG

  1. Random Integer: Randomly selects a number between two specified whole numbers, inclusive:

4.4RandomIntegerBlock.PNG

As our coin will have a random whole number (1 or 2), we will use the second of these blocks.

Get the random integer block from the Toolbox and use it to set the value of the coin variable. Then, specify the range to be from 1 to 2 using the number blocks that are provided. This code should go inside the When Button Click handler:

Now, if you were to click the button, coin would ‘flip’ and randomly ‘land’ on 1 (heads) or 2 (tails), but you would only see the heads.jpg image on your screen. Let’s use an If/Else statement to determine when heads.jpg should be shown and when tails.jpg should be shown.

Displaying the Result: If/Else Algorithm

To display the result of the simulated coin flip, we will either display the heads.jpg image or the tails.jpg image. For this, we will need an if/else block that implements the pseudocode algorithm shown on the left in the following table, with the corresponding Thunkable code shown on the right.

IF (coin = 1)

{

DISPLAY( heads.jpg )

}

ELSE

{

DISPLAY( tails.jpg )

}

Coin Flip Simulation Algorithm

Putting these elements together gives us the following algorithm for simulating the flipping of a two-sided coin, both in College Board-style pseudocode and in Thunkable blocks.

WHEN Button1 Click

{

coin ← RANDOM(1,2)

IF (coin = 1)

{

DISPLAY( heads.jpg )

}

ELSE

{

DISPLAY( tails.jpg )

}

}

Testing the App

Now, you have a fully functioning Coin Flip app that simulates the flipping of a two-sided coin. Test out your app to make sure it works correctly. How accurately can you predict whether the next ‘flip’ will be heads or tails? If you can’t predict any more accurately than flipping a real coin, then we have created a pretty good computer model or computer simulation of a coin flip.

How Does a Computer Model Randomness

Thunkable -- and other computer languages -- use a form of randomness called pseudo randomness. Pseudo randomness is a model (or simulation) of true randomness. Just like your app models or simulates a coin flip, the Thunkable blocks random-fraction and random-integer, which we used to generate random numbers, are models or simulations of truly random numbers. In fact, there are algorithms in Thunkable, known as Pseudo Random Number Generators or PRNGs, that simulate the generation of random numbers. We will take a closer look at how PRNGs work in an upcoming lesson.

As we will learn later in the course when we talk about encryption, the development of secure networks -- such as the Internet -- depends in crucial ways on the development of good PRNGs. So, this is an important area of research in computer science and related fields of mathematics.

Repeating the Coin Flip

Now that we know how to model a coin flip, let’s modify our app so that it will let us perform the following modeling experiment:

Let the user input a number, N, and press a “Run Experiment” button that will cause the app to simulate N coin flips and report the number of heads and the number of tails.

If we did this experiment with a real (fair) coin, we would expect to get roughly 50% heads.

If Thunkable’s random-integer function is well-designed, we should similarly expect to get roughly 50% heads when we perform this simulation experiment.

Revise the UI.

Let’s add the following to the bottom of the UI so it looks like this:

  • Add a label with the text “Coin Flip Experiment”.

  • Add a Label and a TextInput. This Label should be named LabelN with text “N:” and the TextInput should be named TextInputN and have its Keyboard property set to numeric.

  • Add a button named ButtonGo with text to “Run Experiment”.

  • Add another label named LabelResults with text “Results”. This is where we will display the results of the experiment.

Experiment Variables

Clearly, we’re going to need some additional variables to manage the experiment. Add the following variables to the app:

  • N - initialize N to 0. This will be the number of coin flips based on the user’s input in the TextBox.

  • nHeads - initialized to 0. We’ll use this variable to count the number of heads in the experiment.

Coding the Loop

What kind of problem are we using the loop to solve? Basically, if the user inputs 100, we want to flip the coin 100 times, and on each flip, we want to test whether it comes up heads or tails. This is a counting problem - i.e., we need to count the coin flips, repeating N times (whatever the user input). We can use the repeat __ timesarrow-up-right block for this.

In our case, we want to replace the 10 by N, the total number of coin flips to perform:

The loop will repeatedly perform whatever operations we put inside its do slot.

Before the Loop: Initializations

When you’re coding a loop, it is necessary to perform some initialization steps. In this case, we need to set the value of N, which will control the number of iterations for the loop. This variable will be initialized by taking the value the user inputs into the TextInput. And we need to initialize nHeads to 0 -- because, as we’re going to be counting the number of heads we get, we want to start counting at 0:

The Body of The Loop: N Coin Flips

What needs to be done in the body of the loop -- i.e., in the do slot? We need to “flip” the coin and then count whether it came out heads or tails. We already know how to do this using the random integer block for the coin flip and an if/else for checking whether it’s heads or tails. In this case, however, rather than displaying a heads or tails image, we’re going to add 1 to the nHeads variable.

After the Loop: Report Results

When the loop finishes, we will report the results in the LabelResults. Here’s the format we will use:

Heads: 52 Tails: 48

We can do this by using string concatenation (the join block) as follows:

Notice here that the number of tails is calculated by simply subtracting the nHeads from N.

The Whole Algorithm

All of these steps are combined into a single algorithm in the When ButtonGo Click event handler, as shown in the following table in both Thunkable and pseudocode.

Pseudocode

WHEN ButtonGo.Click

{

N ← INPUT()

nHeads ← 0

REPEAT N TIMES

{

coin ← RANDOM(1,2)

IF (coin = 1)

{

nHeads ← nHeads + 1

}

}

DISPLAY( “Heads:”, nHeads,” Tails:”, (N - nHeads) )

}

Running and Testing the App

If you have coded the app as shown here, then whenever ButtonGo the app will perform one trial of the experiment consisting of N simulated coin flips. Try varying the value for N -- you can try 100, or 1000, or 10,000, or any other value. NOTE: Be careful with very large values of N -- that might take a long time, causing your device to become unresponsive.

In the next lesson, we’re going to use this app to run an experiment designed to test the validity of Thunkable’s random integer block.

4.5.3. Summary

In this lesson, you learned how to:

Learning Objective AAP-2.M.a: For algorithms: a. Create algorithms.

Learning Objective AAP-2.M.b: For algorithms: b. Combine and modify existing algorithms.

Learning Objective AAP-3.E.a: For generating random values: a. Write expressions to generate possible values.

Learning Objective AAP-3.E.b: For generating random values: b. Evaluate expressions to determine the possible results.

4.5.4. Still Curious?

Are coin flips fair? While it might be the case that the coin itself is fair — i.e., it favors neither heads nor tails — perhaps the act of flipping a coin is not fair. This NPR storyarrow-up-right reports on experiments that suggest that coin flips are slightly biased towards heads.

4.5.5. Self-Check

Here is a table of the technical terms introduced in this lesson. Hover over the terms to review the definitions.

model

random

random event

random number generator

Q-1: Which of the following would be examples of random events? (Choose all that apply)

A. Dealing a hand of poker.

B. Rolling a 12-sided die.

C. Choosing a ball from a black jar filled with red and green balls.

D. Counting by 2s up to 20.

E. Flipping a coin that has 3 sides.

Q-2: For the following block what possible values would be assigned to X?

A. 1, 2, or 3

B. 1 or 2

C. 1

D. 1 or 3

Q-3: For the following block what value would be assigned to Label1? Type your answer into the text box. (Spelling counts. Don’t use quotes.).

Q-4: Which of the following values could NOT be generated by the random-fraction block?

A. C. 0.5

B. D. 1

C. A. 0

D. B. 0.99

Q-5: For the following block what value would be assigned to Label1? Type your answer into the textbox. (Spelling counts. Don’t use quotes.).

Q-6: AP 2021 Sample Question: A list of numbers has n elements, indexed from 1 to n. The following algorithm is intended to display the number of elements in the list that have a value greater than 100. The algorithm uses the variables count and position. Steps 3 and 4 are missing.

Step 1: Set count to 0 and position to 1.

Step 2: If the value of the element at index position is greaterthan 100, increase the value of count by 1.

Step 3: (missing step)

Step 4: (missing step)

Step 5: Display the value of count.

Which of the following could be used to replace steps 3 and 4 so that the algorithm works as intended?

A. Step 3: Increase the value of position by 1.

Step 4: Repeat steps 2 and 3 until the value of position is greater than n.

B. Step 3: Repeat step 2 until the value of count is greater than 100.

Step 4: Increase the value of position by 1.

C. Step 3: Increase the value of position by 1.

Step 4: Repeat steps 2 and 3 until the value of count is greater than 100.

D. Step 3: Repeat step 2 until the value of position is greater than n.

Step 4: Increase the value of count by 1.

4.5.6. Reflection: For Your Portfolio

Answer the following portfolio reflection questions as directed by your instructor. Questions are also available in this Google Docarrow-up-right where you may use File > Make a Copy to make your own editable copy.

Last updated