Sampling an integer-shape gamma distribution (source code)

= Sampling an integer-shape gamma distribution

Let $m$ be a positive <integer>, $r>0$, and $U_1,\ldots,U_m$ <independent> <uniform random variables> on $(0,1)$. Then
$$
X=-\frac1r\sum_{j=1}^m\log U_j
$$
has a <gamma distribution> of shape $m$ and rate $r$, also called an <Erlang distribution>. The unit <interval> is essential: an unspecified <uniform distribution> on another <interval> would not give this algorithm.

For $t\geq0$, $\mathbb P(-\log U_j/r>t)=\mathbb P(U_j<e^{-rt})=e^{-rt}$. Each summand therefore has an <exponential distribution> with rate $r$, and <additivity of independent gamma distributions with a common rate> proves the result. For $m=3,r=2$, the output has <expected value> $3/2$ and <variance> $3/4$. The formula directly covers <integer> shapes; replacing $m$ by a noninteger number of draws does not define a sampler for a general gamma shape.