Skip to content

Instantly share code, notes, and snippets.

@dsetzer
Last active June 10, 2020 05:21
Show Gist options
  • Save dsetzer/d37e57e85a8ee4d8448c05083c178209 to your computer and use it in GitHub Desktop.
Save dsetzer/d37e57e85a8ee4d8448c05083c178209 to your computer and use it in GitHub Desktop.
Iterative run streak probability. [Possibly incorrect, if any math genius sees a flaw please let me know!]
// Probability of 1,2,3,...s or more streaks of r or more consecutive heads in n tosses
// of a coin having probability p of heads. Returns s values.
//
// P(j, i) = P(j, i - 1) + [P(j-1, i-r-1) - P(j, i-r-1)] * (1-p)p^r, for i > j*(r+1) - 1
//
// P(j, i) = p^(jr) * (1-p)^(j-1), for i = j*(r+1) - 1
//
// P(j, i) = 0, for i < j*(r+1) - 1
//
// P(0, i-r-1) = 1
//
// where j is the number of streaks, and i is the flip.
// Note that [P(j-1, i-r-1) - P(j, i-r-1)]is the probability of exactly j-1 streaks.
// j is taken modulo 2 in the code implementation.
// P is implmented as a linear array prob of size 0:n.
function ProbRunMulti(n, r, p, s) {
let out = [s]
let prob = [n]
for (let i = 0; i < n; i++) {
prob[i] = [r];
}
let c = Math.pow((1 - p) * p, r);
let curr, prev, first, i, j;
if (r <= n) prob[1,r] = Math.pow(p, r);
for (i = (r + 1); i <= n; i++) {
prob[1,i] = prob[1,i - 1] + (1 - prob[1,i - r - 1]) * c;
}
out[0] = prob[1,n];
for (j = 1; j < s; j++) {
curr = j % 2
prev = (j + 1) % 2
first = j * (r + 1) - 1;
if (first <= n) prob[curr,first] = Math.pow(p, (j * r)) * Math.pow((1 - p), (j - 1));
for (i = (first + 1); i <= n; i++) {
prob[curr,i] = prob[j,i - 1] + (prob[prev,(i - r - 1)] - prob[curr,(i - r - 1)]) * c;
}
out[j] = prob[curr,n];
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment