TITLE: How to sample a binomial random variable?
QUESTION [6 upvotes]: Rather than using mathematical libraries, how would you sample from a binomial random variable efficiently?
Given the binomial random variable X, where $k$ are the number of successes in $n$ trials with a success probability of $p$
$$
    P(X=k|n, p) = \binom{n}{k} p^k(1-p)^{n-k},
$$
how could I obtain $N$ number of samples of $X$?
The naïve approach is to decompose $X$ into $X = Y_1 + Y_2 + ... + Y_n$, where $Y$ are the bernoulli experiments 
$$
Y_i = P(Y_i = 1) = p.
$$
Or, in other words, I can test $n$ times if some random value is above $p$ and count how many times this was a success. This is, however, terribly inefficient when $n$ is large.
It is possible to sample a continuous random variable by finding the inverse CDF ($F^{-1}(x)$), sampling from the uniform distribution $ u = U(0,1)$ and calculating the value of the sample in the inverse CDF $F^{-1}(u)$. Given that this is a discrete distribution, how could I apply this? Which other methods are available?

REPLY [3 votes]: A method for the general discrete case is called the alias method. This performs a preprocessing procedure, which can be done in $O(n)$ time*. This converts the $n$ values and probabilities into $n$ "bins", each of which contains either $1$ or $2$ values and some of their probabilities. The construction ensures that each bin has equal total probability. Thus, to sample, you uniformly choose a bin. Then you sample from the two values using their relative probabilities within the bin.
Using the alias method, the sampling time is almost entirely accounted for by the time to generate a sufficiently precise uniform random variable in order to resolve the probabilities within the bins. This is pretty fast; for most practical purposes it can be considered constant time. In particular, it is faster than the $\log(n)$ time that would be required for binary search with a CDF lookup table.
* Note that a naive implementation of the preprocessor chooses the value with the smallest probability (say $m$) to be one half of the bin and the value with the largest probability to be the  maximum probability (say $M$) to be the largest one. This works well for theory because it makes it more obvious that you can always continue the procedure, but it slows down the implementation because you have to figure out where to put $M$ now that you've subtracted probability from it. Doing that bumps the complexity of the preprocessor up to $O(n\log(n))$. But this is not necessary: all that matters is that the values with probability less than $1/n$ are in one place while the values with probability more than $1/n$ are in another. Thus you do need to find a place to put $M$, but it is easy to do so, just check whether the new value of $P(M)$ is less than $1/n$ or greater than $1/n$.
Reference: http://www.jstor.org/stable/2683739 (many other references can be found).