I need to generate random numbers from Binomial(n, p) distribution.
A Binomial(n, p) random variable is sum of n uniform variables which take 1 with probability p. In pseudo code, x=0; for(i=0; I<n; ++I) x+=(rand()<p?1:0);
will generate a Binomial(n, p).
I need to generate this for small as well as really large n, for example n = 10^6 and p=0.02. Is there any fast numerical algorithm to generate it?
EDIT -
Right now this is what I have as approximation (along with functions for exact Poisson and Normal distribution)-
public long Binomial(long n, double p) {
// As of now it is an approximation
if (n < 1000) {
long result = 0;
for (int i=0; i<n; ++i)
if (random.NextDouble() < p) result++;
return result;
}
if (n * p < 10) return Poisson(n * p);
else if (n * (1 - p) < 10) return n - Poisson(n * p);
else {
long v = (long)(0.5 + nextNormal(n * p, Math.Sqrt(n * p * (1 - p))));
if (v < 0) v = 0;
else if (v > n) v = n;
return v;
}
}