Simulating a probability problem with code

Simulating a probability problem with code
0

#1

I was watching a video on Khan Academy about how to compute the probability of getting two heads in a row, given the following:

You have a bag of 8 coins, 5 of which are fair, and 3 of which has a slightly higher chance of getting a head (60% chance). You’ll randomly pick one coin and flip it twice. What’s the probability of getting two heads?

According to Sal (the guy in the video) there’s a 29.125% chance of getting two heads, but I’m not quite convinced, so I wrote some code to simulate the problem.

// The numbers represent the chance of getting a head (out of 10)
var headProbs = [
    // 5 fair coins
    5, 5, 5, 5, 5,
    // 3 unfair coins
    6, 6, 6
];

var count = 0;
var max = 1e6;

for (var i = 0; i < max; i++) {
    // Get a random coin
    var rand = Math.floor(Math.random() * 8);
    var headProb = headProbs[rand];

    // Do two coin flips
    // Muliply by 10 so it's easier to compare with the value in `headProb`
    // By the way this will produce an integer from 0 to 9.
    var flip1 = Math.floor(Math.random() * 10);
    var flip2 = Math.floor(Math.random() * 10);
    
    if (flip1 < headProb && flip2 < headProb) {
        count++;
    }
}

var percent = count / max * 100;

console.log(`Out of ${max} runs, ${count} produced two heads.`);
console.log(`Percentage is ${percent.toFixed(3)}%.`);
console.log('Calculated probability is 29.125%');

These are some of the results:

Out of 1000000 runs, 291343 produced two heads.
Percentage is 29.134%.
Calculated probability is 29.125%

Out of 1000000 runs, 291363 produced two heads.
Percentage is 29.136%.
Calculated probability is 29.125%

Out of 1000000 runs, 290695 produced two heads.
Percentage is 29.069%.
Calculated probability is 29.125%

Assuming my code is correct, I find this convincing. I also find it fun to see that the results produced by simulations match up with calculations :slight_smile: