---
title: "Lab: distributions in code"
heading: Sampling, histograms, the central limit theorem and extremes
eyebrow: A11 · Lesson 19 · Lab: distributions in code
xp: 60
---

::: hook
Lessons 9 to 18 introduced the standard distributions and what happens when random values are transformed, summed and maximized. In this lab you'll generate them yourself: build a Gaussian from twelve uniforms, as early computers did, make exponential samples from uniform ones, compare the binomial with its Poisson approximation, estimate a density from a histogram, and measure the largest of many values against the formula.
:::

::: play
- The curve is the density of the sum of $n$ independent uniform values on $[-\frac12, \frac12]$, scaled to unit variance: a box for $n = 1$, a triangle for 2, and for 3 a smooth hump made of parabolas.
- Already at $n = 3$ it's close to the Gaussian (dashed). That's the central limit theorem at work.
- The readout is the fraction outside $\pm2$ for the Gaussian, which the sum approaches.
:::

```sim plot
view: graph
x: x = -3.5..3.5
y: density = 0..0.6
slider: n = 1..3 step 1 = 2
plot: step(1.5 - n)*step(sqrt(3) - abs(x))/(2*sqrt(3)) + step(n - 1.5)*step(2.5 - n)*step(sqrt(6) - abs(x))*(sqrt(6) - abs(x))/6 + step(n - 2.5)*(step(1 - abs(x))*(3 - x^2)/8 + step(abs(x) - 1)*step(3 - abs(x))*(3 - abs(x))^2/16) | label: sum of n uniforms | samples: 600
plot: exp(-x^2/2)/sqrt(2*pi) | dashed | color: ch2 | label: Gaussian | samples: 600
readout: Gaussian fraction beyond ±2 = 2*Q(2) | digits: 4
```

::: predict
## Twelve independent uniform values on $[0, 1)$ are added and 6 is subtracted. What are the result's mean and standard deviation?

- [x] Mean 0, standard deviation 1
- [ ] Mean 0, standard deviation 12
- [ ] Mean 6, standard deviation 1
- [ ] Mean 0, standard deviation $\sqrt{12}$

::: reveal
Mean 0 and standard deviation 1. Each uniform has mean $\frac12$ and variance $\frac{1}{12}$; twelve of them have mean 6 and variance 1. Subtracting 6 centers it. By the central limit theorem the result is very nearly Gaussian, which made this a cheap way to generate Gaussian noise on early computers. Its one flaw: it can never exceed ±6.
:::
:::

::: nameit
## Making samples

- **Uniform:** `rng.random(n)`.
- **Gaussian:** `rng.normal(mu, sigma, n)`; or, from first principles, a sum of uniforms, or the Box–Muller transform.
- **Any distribution with an invertible CDF** $F$: draw $U$ uniform and return $F^{-1}(U)$. For the exponential, $F^{-1}(u) = -\frac{\ln(1 - u)}{\lambda}$.
- **Discrete:** `rng.binomial(n, p, size)` and `rng.poisson(lam, size)`.

## Checking samples

- Compare the sample mean and standard deviation with the formulas.
- A histogram, with counts divided by the number of samples and the bin width, estimates the density.
- Tail fractions test the shape where approximations fail first: the twelve-uniform Gaussian has slightly too few values beyond $\pm2$.

## Exact probabilities by summation

`math.comb(n, k)` gives binomial coefficients exactly, so binomial probabilities can be summed directly and compared with the Poisson approximation $e^{-\lambda}\frac{\lambda^k}{k!}$ with $\lambda = np$.
:::

::: example
## Compare the binomial and Poisson probabilities of at most 2 errors in 1000 bits at a BER of 0.003.

::: solution
1. **Binomial.**
   $$\begin{aligned} P &= \sum_{k=0}^2\binom{1000}{k}0.003^k0.997^{1000-k} \\ &= 0.42285 \end{aligned}$$
2. **Poisson with $\lambda = 3$.**
   $$\begin{aligned} P &= e^{-3}(1 + 3 + 4.5) \\ &= 0.42319 \end{aligned}$$
3. **Compare.** They agree to 0.1%: with many trials and a small probability, the Poisson form is all you need.

**Answer:** the binomial gives 0.42285 and the Poisson 0.42319, agreeing to 0.1%.
:::
:::

::: example
## A histogram of a million standard Gaussian samples has a bin from $-0.05$ to $0.05$. What count should it hold?

::: solution
1. **Density at 0.**
   $$\frac{1}{\sqrt{2\pi}} = 0.399$$
2. **Expected count.** A bin of width 0.1 holds about
   $$0.0399 \times 10^6 = 39\,900$$
   samples, slightly fewer because the density falls a little across the bin.
3. **Compare with a run.** One run gives 39 534.
4. **Estimate the density.** Counts divided by $N \times$ width estimate the density, 0.395 here.

**Answer:** the bin should hold a little under 39 900 samples.
:::
:::

::: check
given: n = 3 | 24 | 48
answer: sqrt(n/12)
tolerance: 0.5%

## What is the standard deviation of the sum of {n} independent uniform values on $[0, 1)$?

::: right
Right. Each has variance $\frac{1}{12}$, so the sum has variance $\frac{n}{12}$ and standard deviation {answer}.
:::

::: misses
- [n/12] That's the variance.
- [sqrt(n)/2] Each uniform's standard deviation is $\frac{1}{\sqrt{12}}$, not $\frac12$.
- [any] Not yet. Variances add.
:::
:::

::: check
given: l = 0.5 | 2 | 5; u = 0.5 | 0.9
answer: -ln(1 - u)/l
tolerance: 0.5%

## An exponential sampler with rate {l} uses $y = -\frac{\ln(1 - u)}{\lambda}$. What does $u$ = {u} give?

::: right
Right. {answer}.
:::

::: misses
- [-log(1 - u)/l] Use the natural logarithm.
- [any] Not yet. $-\frac{\ln(1 - u)}{\lambda}$.
:::
:::

::: check
kind: python

## Make 10⁶ samples by adding 12 uniforms and subtracting 6 (`rng = np.random.default_rng(1)`). Set `sd` to their standard deviation and `tail` to the fraction beyond ±2.

```python starter
import numpy as np

sd = tail = 0.0
print(sd, tail)
```

```python solution
import numpy as np

rng = np.random.default_rng(1)
x = rng.random((10**6, 12)).sum(axis=1) - 6
sd = x.std()
tail = np.mean(np.abs(x) > 2)
print(sd, tail)
```

```python tests
assert abs(sd - 1) < 0.003, f"The standard deviation should be 1; got {sd}."
assert 0.043 < tail < 0.0455, f"The tail should be just under the Gaussian's 0.0455; got {tail}."
```

::: right
Right. The standard deviation is spot on; the tail is slightly thin, about 0.0446 against 0.0455, because twelve uniforms can't reach far out.
:::
:::

::: check
kind: python

## Make 10⁵ exponential samples with rate 2 by the inverse-CDF method (`np.random.default_rng(2)`). Set `mean` and `frac` (the fraction below the mean, 0.5).

```python starter
import numpy as np

mean = frac = 0.0
print(mean, frac)
```

```python solution
import numpy as np

rng = np.random.default_rng(2)
y = -np.log(1 - rng.random(10**5)) / 2
mean = y.mean()
frac = np.mean(y < 0.5)
print(mean, frac)
```

```python tests
import math
assert abs(mean - 0.5) < 0.005, f"The mean should be 1/lambda = 0.5; got {mean}."
assert abs(frac - (1 - math.exp(-1))) < 0.005, f"A fraction 1 - 1/e = 0.632 should lie below the mean; got {frac}."
```

::: right
Right. More than half the samples are below the mean: the long tail pulls the mean up.
:::
:::

::: check
kind: python

## Set `binom` to the exact probability of at most 2 errors in 1000 bits at BER 0.003 (use `math.comb`), and `poisson` to the Poisson approximation.

```python starter
import math

binom = poisson = 0.0
print(binom, poisson)
```

```python solution
import math

binom = sum(math.comb(1000, k) * 0.003**k * 0.997**(1000 - k) for k in range(3))
poisson = math.exp(-3) * (1 + 3 + 9 / 2)
print(binom, poisson)
```

```python tests
assert abs(binom - 0.422853) < 1e-6, f"The binomial sum is 0.42285; got {binom}."
assert abs(poisson - 0.423190) < 1e-6, f"The Poisson value is 0.42319; got {poisson}."
```

::: right
Right. They differ in the fourth digit: Poisson is an excellent approximation here.
:::
:::

::: check
kind: python

## Estimate the standard Gaussian density at 0 from 10⁶ samples (`np.random.default_rng(3)`), using the fraction in $[-0.025, 0.025]$ divided by the bin width. Set `dens`.

```python starter
import numpy as np

dens = 0.0
print(dens)
```

```python solution
import numpy as np

rng = np.random.default_rng(3)
y = rng.normal(size=10**6)
dens = np.mean(np.abs(y) < 0.025) / 0.05
print(dens)
```

```python tests
import math
assert abs(dens - 1 / math.sqrt(2 * math.pi)) < 0.01, f"The density at 0 is 0.399; got {dens}."
```

::: right
Right. A narrow bin estimates the density closely; the price is more random scatter, since fewer samples land in it.
:::
:::

::: check
kind: python

## Draw 10⁵ sets of 9 uniform values (`np.random.default_rng(4)`), take the largest of each, and set `mean_max` and `below` (the fraction of maxima below 0.9).

```python starter
import numpy as np

mean_max = below = 0.0
print(mean_max, below)
```

```python solution
import numpy as np

rng = np.random.default_rng(4)
m = rng.random((10**5, 9)).max(axis=1)
mean_max = m.mean()
below = np.mean(m < 0.9)
print(mean_max, below)
```

```python tests
assert abs(mean_max - 0.9) < 0.002, f"The mean of the maximum is n/(n + 1) = 0.9; got {mean_max}."
assert abs(below - 0.9**9) < 0.005, f"The chance it's below 0.9 is 0.9^9 = 0.387; got {below}."
```

::: right
Right. Both match lesson 18's formulas: $\frac{n}{n + 1}$ and $F^n$.
:::
:::

::: explain
## Why does adding up many independent random values give a Gaussian, whatever their own distribution?

::: model
Each value contributes its own small, independent nudge to the sum, and the sum's distribution is the convolution of all their distributions. Convolving smooths: a box convolved with a box is a triangle, the triangle with another box a curve made of parabolas, and each further convolution rounds the shape more. In the frequency domain, convolution is multiplication of characteristic functions, and the product of many functions that each start at 1 with zero slope and some curvature tends to $e^{-\sigma^2\omega^2/2}$, whose inverse is a Gaussian. Only the means and variances survive, as long as no single term dominates. That's why noise made of many small independent sources, like thermal noise, is Gaussian.
:::
:::

::: practice

::: check
given: n = 1..100 int
answer: sqrt(n/12)
tolerance: 0.5%

## Standard deviation of a sum of {n} uniforms on $[0, 1)$?

::: misses
- [any] $\sqrt{n/12}$.
:::
:::

::: check
given: l = 0.1..10; u = 0.01..0.99
answer: -ln(1 - u)/l
tolerance: 0.5%

## Inverse-CDF exponential sample, rate {l}, $u$ = {u}?

::: misses
- [any] $-\frac{\ln(1 - u)}{\lambda}$.
:::
:::
:::
