Last active
November 8, 2021 18:26
-
-
Save dsetzer/11a516039d2c0b8899c55ba5ac0eaea8 to your computer and use it in GitHub Desktop.
Iterative run probability
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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