Simulation 1

For this section we use loops to run little random scenarios -- like flipping a coin -- thousands of times to see what outcomes we get. In this way, the computer works as a sort of telescope, giving us insight about the space of outcomes but without requiring us to do any formal mathematics. Just run the simulation and see what it does! This is also known as "monte carlo simulation".

Class technique: can have students flip coins or dice or whatever, write sums on the board to try experiments by hand before doing them on the computer.

For the simulation code, the function call random(1, 6) returns a random number in between the two numbers (inclusive), so the result of random(1, 6) is like rolling a 6-sided die, and random(1, 2) is like flipping a coin.

The strategy will have an outer loop to run, say, 1000 trials. Inside the loop we have the code to run one trial. The function series(1000) returns a collection of the numbers 1, 2, 3... 1000. Using this, we can write a loop to iterate 1000 (or whatever number) times, like this

for (i: series(1000)) {
  ...
}

To record what happens, we'll use the Histogram(min, max) class. Use histogram.add(val) to record one trial value, and print(histogram) to print its current state. The following code example demonstrates the use of all these functions:

Coin Example 1

Flip a coin 100 times. How many times does heads come up? Try increasing the number of trials up from 100.


Coin Example 2

Say we flip 2 coins. How often will we get heads on both coins?


Coin Example 3

Say we flip 2 coins. How often will the two coins be the same?


Coin Problems

Now the code is not included, so there are two problems: what its the that implements the experiment, and what numerically is the answer?

Coin Problem 4

Say we flip 2 coins. How often do we get at least one head across the 2 coins?


  // your code here
  if (a == 1 || b == 1) {  // at least one heads
    histogram.add(1);
  }

Coin Problem 5

Say we flip 3 coins, a b c. If a is tails, you automatically lose. If a is heads, then if at least one of b or c is tails, you win. How often do you win?


  // your code here
  if (a == 1 && (b == 2 || c == 2)) {
    histogram.add(1);
  }
  // Works out to 37.5%
  // Note: parenthesis are needed to make the &&/|| precedence correct