Skip to content

Instantly share code, notes, and snippets.

@dsetzer
Last active November 8, 2021 18:26
Show Gist options
  • Select an option

  • Save dsetzer/11a516039d2c0b8899c55ba5ac0eaea8 to your computer and use it in GitHub Desktop.

Select an option

Save dsetzer/11a516039d2c0b8899c55ba5ac0eaea8 to your computer and use it in GitHub Desktop.
Iterative run probability
// Probability of a r or more consecutive heads in n tosses
// of a coin having probability p of heads
// P(i) = P(i-1) + [1 - P(i-r-1)] * (1-p)p^r, for i > r
// P(r) = p^r
// P(i) = 0, for i < r
// where i is the flip.
// P is implemented as a circular array prob of size 0:r.
function ProbRun(n, r, p) {
let prob = [r], iter, last, i, j;
let c = (1 - p) * Math.pow(p, r);
iter = n / (r + 1)
last = Math.round(n - iter * (r + 1));
c = (1 - p) * Math.pow(p, r);
prob[r] = Math.pow(p, r);
for (j = 1; j < iter; j++) {
prob[0] = prob[r] + (1 - prob[0]) * c;
for (i = 1; i < r; i++) {
prob[i] = prob[i - 1] + (1 - prob[i]) * c
}
}
return prob[last];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment