I've read this and come up with a function: https://www.quora.com/What-is-the-probability-that-we-will-flip-at-least-8-heads-out-of-10-flips
function findAtLeastKInN(k,n, itemProbability) {
var probabilities = []
for(var x=k; x<=n; x++) {
probabilities.push(probabilityOfExactkyKInN(x,n,itemProbability))
}
return probabilities.reduce(function(acc,x) {
return acc+x
},0)
}
function probabilityOfExactkyKInN(k,n,itemProbability) {
var probabilityOfNotItem = (1-itemProbability)
return Math.pow(probabilityOfNotItem, n-k)*Math.pow(itemProbability, k)*choose(n,k)
}
function choose(n,k) {
if(k===0)
return 1
else
return fac(n)/(fac(k)*fac(n-k))
}
// factorial
function fac(x) {
var product = 1
for(var a=2;a<=x;a++) {
product *= a
}
return product
}
It seems to come to the same probability as given in the quora answer for findAtLeastKInN(8, 10, .5), but findAtLeastKInN(50, 100, .5) seems to return something other than the expected .5 . Is there something wrong with my function? Or am I misunderstanding how the probabilities would work out somehow?
The reason that
findAtLeastKInN(50, 100, .5)does not (and should not) return the answer $0.5$ is that the chance of getting more than $50$ heads is exactly equal to the chance of getting fewer than $50$ heads, while there is also a significant chance of getting exactly $50$ heads.That is, if $X$ is the number of heads in $100$ tosses of a fair coin, $$ P(X < 50) + P(X = 50) + P(X > 50) = 1, $$ but $P(X < 50) = P(X > 50),$ so $$ P(X = 50) + 2P(X > 50) = 1, $$ therefore $$ \tfrac12 P(X = 50) + P(X > 50) = \tfrac12, $$ therefore $$ P(X \geq 50) = P(X = 50) + P(X > 50) = \tfrac12 + \tfrac12 P(X = 50). $$
It turns out that $P(X = 50) \approx 0.0795892$ and therefore $P(X \geq 50) \approx 0.539795$.
If you want to give the function some large inputs such that the mathematically exact result would be $0.5,$ try to avoid the "exactly half" outcome.
For example, you could try
findAtLeastKInN(50, 99, .5), in which the set of fifty possible outcomes $\{0,1,2,\ldots,49\}$ should be exactly as likely as the set of fifty possible outcomes $\{50,51,52,\ldots,99\}.$