I'm simulating a number of low probability random events and I want to get the total number that occur with $n$ simulations (not the expected number, the actually number) by rolling a single random number. So going from this
$N = \sum\limits_{i=1}^n \begin{cases} 1,& \text{if } random(0,1)\leq p\\ 0, & \text{otherwise} \end{cases} $
Where $p$ is the probability of each single event occurring, and random(0,1) is an evenly distributed random function outputting between 0 and 1, $N$ is the number of events that succeed and $n$ is the number of tries.
Getting the expected number is easy $N_e = pn$. but I'm looking to actually run this with a real random number generator and get the actual result (e.g. in a toss of 300 coins you'll expect to get 150 heads but you might get 300)
Effectively what I'm trying to do is to eliminate the sum in a way that maintains the standard deviation and make only a single call to the function random(0,1)
In the case of flipping 3 coins with probability 0.5 I'd therefore expand this to:
$N = \begin{cases} 3, & 0.875 \lt r \leq 1\\ 2, & 0.5 \lt r \leq 0.875\\ 1,& 0.125 \lt r \leq 0.5 \\ 0, &0 \lt r \leq 0.125 \\ \end{cases} $
where r is a single call to random(0,1)
But that is obviously a very specific case, expecially the 0.5 probability which makes everything easier, is there a way to do this in the general case?
The probability of getting a particular number of successes is:
$P_N = numberOfCombinations * probabilityOfCombination $
$P_N = \frac{n!}{N!(n-N)!} p^Np^{(n-N)}$
where $N$ is the number of successes, $n$ is the number of tries and $p$ is the probability of success
So this is the size of the region that should be mapped to the $r$, what region it is doesn't really matter, so the region of the single call to $random(0,1)$ that $r$ should take to provide $N$ successes is:
$ \sum\limits_{m=1}^{N-1} \frac{n!}{m!(n-m)!} p^mp^{(n-m)} \lt r \lt \sum\limits_{m=1}^{N} \frac{n!}{m!(n-m)!} p^mp^{(n-m)} $