Skip to content

Instantly share code, notes, and snippets.

@nemtsov
Created April 9, 2014 04:31
Show Gist options
  • Save nemtsov/10226241 to your computer and use it in GitHub Desktop.
Save nemtsov/10226241 to your computer and use it in GitHub Desktop.
Coin toss probability simulator
/**
* "What is the probability of getting
* 7 tails in a row, out of 150 tosses
* of a fair coin?"
*/
function experiment(streak, tosses) {
var i, ctr = 0;
for (i = 0; i < tosses; i++) {
if (Math.random() < 0.5) ctr = 0;
else if (++ctr === streak) return 1;
}
return 0;
}
function run(streak, tosses, runs) {
var i, total = 0;
for (i = 0; i < runs; i++) {
total += experiment(streak, tosses);
}
return total / runs;
}
console.log('\nP(A) = %s\n',
run(7, 150, 1e6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment