---
title: Moment generating functions
heading: One function that holds every moment, and turns sums into products
eyebrow: A11 · Lesson 26 · Moment generating functions
xp: 40
---

::: hook
Lesson 25 found the distribution of a sum of independent variables by convolving their densities, which is hard work beyond two or three terms. A total delay through three exponential queues, the count from two independent Poisson sources, the noise from many small contributions: each is a sum. There's a transform that turns convolution into multiplication, just as the Fourier and Laplace transforms do for signals: the **moment generating function**. It also produces a variable's mean, variance and every other moment by differentiation, and it's the cleanest way to see why sums tend toward the Gaussian.
:::

::: play
- The curves are the density of the sum of $n$ independent exponential variables, each with mean 1, against the Gaussian with the same mean $n$ and variance $n$.
- For $n = 1$ the two look nothing alike. By $n$ = 20 they nearly coincide: the central limit theorem, which the generating function explains.
:::

```sim plot
view: graph
x: t = 0..40
y: density = 0..0.5
slider: n = 1..20 step 1 = 3
plot: t^(n - 1)*exp(-t)/(n - 1)! | label: sum of n exponentials
plot: exp(-(t - n)^2/(2*n))/sqrt(2*pi*n) | dashed | label: Gaussian, same mean and variance
readout: mean = n | digits: 3
readout: standard deviation = sqrt(n) | digits: 3
```

::: predict
## Two independent sources each emit a Poisson number of photons per millisecond, with means 2 and 3. What is the distribution of the total?

- [x] Poisson with mean 5
- [ ] Gaussian with mean 5
- [ ] The convolution of two Poissons, which has no simple form
- [ ] Poisson with mean 6

::: reveal
Poisson with mean 5. A Poisson variable's generating function is $e^{\lambda(e^s - 1)}$; multiplying two of them gives $e^{(2 + 3)(e^s - 1)}$, which is the generating function of a Poisson with mean 5. The convolution exists, but the generating functions answer the question without doing it.
:::
:::

::: nameit
## The moment generating function

$$M_X(s) = E\left[e^{sX}\right]$$

defined for the real $s$ where the expectation is finite. Expanding $e^{sX} = 1 + sX + s^2X^2/2! + \cdots$ shows where the name comes from:

$$M_X(0) = 1 \qquad M_X'(0) = E[X] \qquad M_X''(0) = E[X^2]$$

so $\text{Var}(X) = M''(0) - M'(0)^2$. (With $s = j\omega$ it's the **characteristic function**, essentially the Fourier transform of the density, which always exists.)

## Sums become products

If $X$ and $Y$ are independent, $E[e^{s(X + Y)}] = E[e^{sX}]E[e^{sY}]$, so

$$M_{X+Y}(s) = M_X(s)\,M_Y(s)$$

and a generating function determines its distribution, so recognizing the product identifies the sum.

## A short table

| Distribution | $M(s)$ |
|---|---|
| Gaussian, mean $\mu$, variance $\sigma^2$ | $e^{\mu s + \sigma^2s^2/2}$ |
| Poisson, mean $\lambda$ | $e^{\lambda(e^s - 1)}$ |
| Exponential, rate $\lambda$ | $\dfrac{\lambda}{\lambda - s}$ for $s < \lambda$ |
| Bernoulli, $P(1) = p$ | $1 - p + pe^s$ |

So sums of independent Gaussians are Gaussian (means and variances add), sums of independent Poissons are Poisson, and a sum of $n$ independent exponentials with rate $\lambda$ has $M = (\lambda/(\lambda - s))^n$: the **Erlang** distribution, the waiting time for the $n$th arrival of a Poisson process (lesson 13), with tail

$$P(T > t) = e^{-\lambda t}\sum_{k=0}^{n-1}\frac{(\lambda t)^k}{k!}$$

## Why sums turn Gaussian

For a variable with mean 0 and variance 1, $\ln M(s) = s^2/2 + O(s^3)$. The sum of $n$ independent copies, scaled by $1/\sqrt n$, has $\ln M = n\ln M(s/\sqrt n) = s^2/2 + O(1/\sqrt n)$, which approaches $s^2/2$, the standard Gaussian's. Every distribution with a finite variance loses its other features under addition; that's lesson 16's central limit theorem.
:::

::: example
## Find the mean and variance of an exponential variable with rate $\lambda$ from its generating function.

::: solution
1. **Differentiate the generating function.**
   $$M(s) = \frac{\lambda}{\lambda - s}$$
   $$M'(s) = \frac{\lambda}{(\lambda - s)^2}$$
   $$M''(s) = \frac{2\lambda}{(\lambda - s)^3}$$
2. **Set $s = 0$.**
   $$E[X] = \frac{1}{\lambda}$$
   $$E[X^2] = \frac{2}{\lambda^2}$$
3. **Variance.**
   $$\begin{aligned} \text{Var}(X) &= \frac{2}{\lambda^2} - \frac{1}{\lambda^2} \\ &= \frac{1}{\lambda^2} \end{aligned}$$
4. **What it means.** The standard deviation equals the mean, the exponential's signature spread.

**Answer:** the mean is $1/\lambda$ and the variance $1/\lambda^2$.
:::
:::

::: example
## A packet passes three independent stages, each taking an exponential time with mean 2 ms. What's the mean and standard deviation of the total, and the chance it exceeds 10 ms?

::: solution
1. **The total's distribution.** Each stage has $\lambda$ = 0.5 per ms, so the total's generating function is
   $$\left(\frac{0.5}{0.5 - s}\right)^3$$
   an Erlang with $n = 3$.
2. **Mean and spread.** The mean is 6 ms and the variance
   $$3 \times 4 = 12\ \text{ms}^2$$
   so the standard deviation is 3.46 ms.
3. **Tail beyond 10 ms.** With $\lambda t$ = 5,
   $$\begin{aligned} P(T > 10) &= e^{-5}\left(1 + 5 + \frac{25}{2}\right) \\ &= 18.5e^{-5} \\ &= 0.125 \end{aligned}$$
4. **Compare with a Gaussian.** One packet in eight takes more than 10 ms; a Gaussian with the same mean and spread would say 0.124, already close at only three stages.

**Answer:** the total has a mean of 6 ms and a standard deviation of 3.46 ms, and exceeds 10 ms with chance 0.125.
:::
:::

::: example
## Two independent Poisson sources emit 2 and 3 photons per millisecond on average. What is the chance of exactly 5 photons in a millisecond?

::: solution
1. **Multiply the generating functions.**
   $$e^{2(e^s - 1)}\,e^{3(e^s - 1)} = e^{5(e^s - 1)}$$
   so the total is Poisson with mean 5.
2. **Exactly 5 photons.**
   $$\begin{aligned} P(5) &= \frac{5^5e^{-5}}{5!} \\ &= 0.175 \end{aligned}$$
3. **The long way.** Without the generating function this would be a sum of six products of Poisson probabilities, which gives the same 0.175 with much more work.

**Answer:** the chance of exactly 5 photons is 0.175.
:::
:::

::: check
given: mu = -1 | 1 | 2; s2 = 0.5 | 1 | 4
answer: mu^2 + s2
tolerance: 0.5%

## A Gaussian variable has $M(s) = e^{\given{mu}s + \given{s2}s^2/2}$. What is $E[X^2]$, from $M''(0)$?

::: right
Right. $M''(0) = \mu^2 + \sigma^2$ = {answer}, the mean squared plus the variance.
:::

::: misses
- [s2] That's the variance. $E[X^2]$ adds the mean squared.
- [mu^2] Add the variance too.
- [any] Not yet. Differentiate twice and set $s = 0$: you get $\mu^2 + \sigma^2$.
:::
:::

::: check
given: m = 1 | 2 | 5; n = 2 | 3 | 5; t = 4 | 10 | 20
answer: exp(-t/m)*(1 + (t/m) + (t/m)^2/2*step(n - 2.5) + (t/m)^3/6*step(n - 3.5) + (t/m)^4/24*step(n - 4.5))
tolerance: 0.5%

## A task passes {n} independent exponential stages, each with mean {m} ms. What's the chance the total exceeds {t} ms?

::: right
Right. The total is Erlang: $P(T > t) = e^{-\lambda t}\sum_{k=0}^{n-1}(\lambda t)^k/k!$ with $\lambda t = \given{t}/\given{m}$: {answer}.
:::

::: misses
- [exp(-t/m)] That's one stage. The sum of {n} stages has a heavier tail, $e^{-\lambda t}\sum_{k<n}(\lambda t)^k/k!$.
- [exp(-t/(n*m))] That treats the total as exponential with the summed mean. It's Erlang, which is far less spread out.
- [any] Not yet. Use the Erlang tail with $\lambda t$ = {t}/{m}.
:::
:::

::: check
given: a = 1 | 2 | 4; b = 0.5 | 3; k = 2 | 4 | 6
answer: (a + b)^k*exp(-(a + b))/k!
tolerance: 0.5%

## Independent Poisson counts have means {a} and {b}. What's the chance their sum equals {k}?

::: right
Right. The generating functions multiply into $e^{(\given{a} + \given{b})(e^s - 1)}$, so the sum is Poisson with mean $\given{a} + \given{b}$: {answer}.
:::

::: misses
- [(a*b)^k*exp(-(a*b))/k!] The means add, they don't multiply.
- [any] Not yet. The sum is Poisson with the summed mean.
:::
:::

::: check
kind: parts
given: lam = 0.5 | 2 | 5

## An exponential variable has rate {lam}, so $M(s) = \lambda/(\lambda - s)$.

::: part
answer: 1/lam
tolerance: 0.5%

### What is its mean, $M'(0)$?

::: misses
- [lam] That's the rate. The mean is $1/\lambda$.
- [any] Not yet. $M'(s) = \lambda/(\lambda - s)^2$.
:::
:::

::: part
answer: 1/lam^2
tolerance: 0.5%

### What is its variance, $M''(0) - M'(0)^2$?

::: misses
- [2/lam^2] That's $E[X^2]$. Subtract the mean squared.
- [any] Not yet. $M''(0) = 2/\lambda^2$; subtract $1/\lambda^2$.
:::
:::

::: right
Right. Mean and standard deviation are equal, $1/\lambda$, for every exponential.
:::
:::

::: check
kind: python
given: lam = 1 | 2; n = 2 | 4; s = 0.2 | 0.5

## Draw 400 000 sums of `n` = {n} independent exponentials with rate `lam` = {lam}, using `rng = np.random.default_rng(1)` and `rng.exponential(1 / lam, (400000, n)).sum(axis=1)`. Set `M_est` to the sample mean of $e^{sT}$ at `s` = {s} (below the rate), `M_exact` to $(\lambda/(\lambda - s))^n$, and `var_est` to the sample variance of the sums, to compare with $n/\lambda^2$.

```python starter
import numpy as np
M_est = M_exact = 1
var_est = 0
print(M_est, M_exact, var_est)
```

```python solution
import numpy as np
rng = np.random.default_rng(1)
T = rng.exponential(1 / lam, (400000, n)).sum(axis=1)
M_est = np.mean(np.exp(s * T))
M_exact = (lam / (lam - s))**n
var_est = T.var()
print(M_est, M_exact, var_est)
```

```python tests
import numpy as np
r = np.random.default_rng(1)
TT = r.exponential(1 / lam, (400000, n)).sum(axis=1)
assert abs(M_exact - (lam / (lam - s))**n) < 1e-12, "M_exact is (λ/(λ − s))^n."
assert abs(M_est - np.mean(np.exp(s * TT))) < 1e-9 * M_est and abs(M_est / M_exact - 1) < 0.05, "The sample mean of e^(sT) should land within a few percent of the exact product."
assert abs(var_est - TT.var()) < 1e-9 and abs(var_est / (n / lam**2) - 1) < 0.02, "The variances add: n/λ²."
```

::: right
Right. The sample average of $e^{sT}$ matches the product of the individual generating functions: independence turns the expectation of a product into a product of expectations.
:::
:::

::: check
kind: derivation
vars: lam = 1..5, s = -1..0.5, x = 0..3

## Derive the exponential's generating function, $M(s) = \int_0^\infty e^{sx}\lambda e^{-\lambda x}\,dx$, for $s < \lambda$.

::: step
answer: lam*exp(-(lam - s)*x)

### Combine the exponentials. What is the integrand?
:::

::: step
answer: lam/(lam - s)

### Integrate from 0 to ∞. What is $M(s)$?
:::

::: right
Right. The integral only converges for $s < \lambda$, which is why generating functions are defined on a range of $s$; the characteristic function, at $s = j\omega$, always converges.
:::
:::

::: check
kind: choice

## Why is the generating function of a sum of independent variables the product of their generating functions?

- [x] Because $e^{s(X + Y)} = e^{sX}e^{sY}$, and the expectation of a product of independent variables is the product of their expectations
- [ ] Because means add
- [ ] It's only true for Gaussian variables
- [ ] Because the generating function is linear

::: right
Right. The exponential turns the sum into a product, and independence lets the expectation split. That's the same reason the Fourier transform turns convolution into multiplication.
:::

::: misses
- [2] Means add for any variables, independent or not, but that's not why generating functions multiply.
- [3] It's true for any independent variables whose generating functions exist.
- [4] The generating function isn't linear in the variable: $M_{2X}(s) = M_X(2s)$, not $2M_X(s)$.
:::
:::

::: explain
## A sum of many small independent noises looks Gaussian whatever the individual noises look like. Use generating functions to explain why.

::: model
Each noise, scaled to mean 0 and variance 1, has a log generating function that starts $s^2/2$ plus higher powers of $s$ that depend on its shape. Summing $n$ of them and dividing by $\sqrt n$ multiplies their generating functions and scales $s$ by $1/\sqrt n$, so the log of the result is $n$ copies of $s^2/2n$ plus higher terms that each shrink as $n^{-1/2}$ or faster. The $s^2/2$ parts add to exactly $s^2/2$, the Gaussian's, while everything that distinguished the individual shapes fades. Only the mean and variance survive the summing.
:::
:::

::: practice

::: check
given: m1 = 1 | 3; v1 = 1 | 4; m2 = -1 | 2; v2 = 0.5 | 2
answer: v1 + v2
tolerance: 0.5%

## Independent Gaussians have variances {v1} and {v2} (means {m1} and {m2}). What is the variance of their sum?

::: misses
- [sqrt(v1) + sqrt(v2)] Variances add, not standard deviations.
- [any] For independent variables, variances add.
:::
:::

::: check
given: p = 0.1 | 0.5; n = 5 | 20
answer: n*p
tolerance: 0.5%

## A count is the sum of {n} independent Bernoulli variables with $P(1)$ = {p}, so $M(s) = (1 - p + pe^s)^n$. What is its mean, $M'(0)$?

::: misses
- [p] That's one trial's mean. Multiply by the number of trials.
- [any] $M'(0) = np$.
:::
:::
:::
