---
title: Counting and ensembles lab
heading: Multiplicities, energy sharing, partition functions and the maximum-entropy principle, computed in Python
eyebrow: B11 · Lesson 5 · Statistics lab
xp: 50
---

::: hook
Lessons 1 to 4 built thermal physics from counting: multiplicities, entropy as their logarithm, temperature from how entropy changes with energy, and the Boltzmann factor for a system in contact with a reservoir. Every one of those ideas can be checked by brute force on a computer, with numbers too large for a calculator. In this lab you'll count states exactly with log-gamma functions, watch two Einstein solids share energy, build a general partition-function calculator, find a Schottky peak numerically, and check that the Boltzmann distribution really is the one with the most entropy.
:::

::: play
- Two Einstein solids with $N_A$ and $N_B$ oscillators share q quanta. The curve is the relative number of ways to give a fraction x of the quanta to A, from Stirling's formula for each solid's multiplicity.
- The peak sits at $\frac{N_A}{N_A + N_B}$: energy divides in proportion to size, which is what equal temperatures mean here.
- Multiply all three sliders by ten and the peak narrows by about $\sqrt{10}$. Step 2 computes the same distribution exactly.
:::

```sim plot
view: graph
x: x = 0.001..0.999
y: P = 0..1.05
slider: A = 10..1000 step 10 = 300
slider: B = 10..1000 step 10 = 200
slider: q = 10..2000 step 10 = 100
plot: exp(((x*q + A)*ln(x*q + A) - x*q*ln(x*q) - A*ln(A)) + (((1 - x)*q + B)*ln((1 - x)*q + B) - (1 - x)*q*ln((1 - x)*q) - B*ln(B)) - ((q*A/(A + B) + A)*ln(q*A/(A + B) + A) - q*A/(A + B)*ln(q*A/(A + B)) - A*ln(A)) - ((q*B/(A + B) + B)*ln(q*B/(A + B) + B) - q*B/(A + B)*ln(q*B/(A + B)) - B*ln(B))) | label: ways, relative to the peak | samples: 800
readout: most probable fraction = A/(A + B) | digits: 3
readout: width σ/q = 1/(q*sqrt(A/((q*A/(A + B))*(q*A/(A + B) + A)) + B/((q*B/(A + B))*(q*B/(A + B) + B)))) | digits: 3
```

::: predict
## Two Einstein solids of 300 and 200 oscillators share 100 quanta. What's the chance that the smaller solid holds more than half of them?

- [ ] About 40%, since it's two-fifths of the oscillators
- [ ] About 20%
- [x] About 4%
- [ ] Less than one in a million

::: reveal
About 4%. The most probable split gives the smaller solid 40 quanta, and the distribution's width is about 5.4 quanta, so 50 or more is nearly two standard deviations out: 3.9% exactly. With systems this small the fluctuations are easy to see; for a mole of oscillators the same question has a probability with an exponent in the trillions.
:::
:::

::: nameit
## Counting with logarithms

Multiplicities overflow floating point almost at once: $\binom{1000}{500}$ is about $10^{299}$, and a gram of anything is beyond any number a computer can hold. So compute $\ln g$ instead, using `math.lgamma(n + 1)` for $\ln n!$, and subtract logarithms before exponentiating. Ratios of multiplicities, which are what probabilities need, come out exactly.

## Two systems sharing energy

An Einstein solid of N oscillators holding q quanta has $\Omega(N, q) = \binom{q + N - 1}{q}$ microstates. When two solids share q quanta, the chance of a split is $\frac{\Omega_A(q_A)\Omega_B(q - q_A)}{\Omega_{A+B}(q)}$. Its peak is where $\frac{\partial\ln\Omega_A}{\partial q_A} = \frac{\partial\ln\Omega_B}{\partial q_B}$, equal temperatures. From Stirling's formula the width is about

$$\sigma^2 = \left[\frac{N_A}{q_A(q_A + N_A)} + \frac{N_B}{q_B(q_B + N_B)}\right]^{-1}$$

at the most probable split.

## A general partition function

For levels $E_i$ with degeneracies $g_i$, $Z = \sum_ig_ie^{-E_i/kT}$. Everything else follows: the probabilities $p_i = g_ie^{-E_i/kT}/Z$, the energy $U = \sum p_iE_i$, the entropy $S = -k\sum_i p_i\ln\frac{p_i}{g_i}$, and the heat capacity from the energy's variance, $C = \frac{\langle E^2\rangle - \langle E\rangle^2}{kT^2}$.

## Maximum entropy

Among all probability distributions over the states with a given average energy, the Boltzmann distribution has the largest entropy. So any change that keeps $\sum p_i = 1$ and $\sum p_iE_i = U$ must lower S, by about $\frac{\varepsilon^2}{2}\sum\frac{d_i^2}{p_i}$ for a small change $\varepsilon d_i$. This is another route to the Boltzmann factor, and the one information theory takes.
:::

::: example
## Two Einstein solids, $N_A$ = 300 and $N_B$ = 200, share 100 quanta. Find the most probable split, its probability, the width of the distribution and the chance that B holds half or more.

::: solution
1. **Most probable split.** Computing all 101 splits exactly, the most probable is $q_A$ = 60, with probability 7.4%, and the mean is also 60.0.
2. **Width.** The standard deviation is 5.36 quanta, and the Stirling estimate gives nearly the same:
   $$\begin{aligned} \sigma &\approx \left[\frac{300}{60 \times 360} + \frac{200}{40 \times 240}\right]^{-1/2} \\ &= 5.37 \end{aligned}$$
3. **B holds half or more.** That means $q_A \le 50$, which has a chance of 3.9%.
4. **Check the counting.** The total number of microstates is
   $$\binom{599}{100} = 9.26 \times 10^{115}$$
   and the sum of all splits reproduces it, a check that the counting is right.

**Answer:** the most probable split is $q_A$ = 60 (probability 7.4%), the standard deviation is 5.36 quanta, and B holds half or more 3.9% of the time.
:::
:::

::: example
## A system has levels at 0, 10 and 20 meV, one state each, at 300 K. Find Z, the probabilities, U and S.

::: solution
1. **Partition function.** kT = 25.85 meV, so
   $$\begin{aligned} Z &= 1 + e^{-0.387} + e^{-0.774} \\ &= 2.140 \end{aligned}$$
2. **Probabilities.** They are 0.467, 0.317 and 0.216.
3. **Average energy.**
   $$\begin{aligned} U &= 10 \times 0.317 + 20 \times 0.216 \\ &= 7.48\ \text{meV} \end{aligned}$$
4. **Entropy.**
   $$\begin{aligned} S &= -k\sum p_i\ln p_i \\ &= 1.05k \end{aligned}$$
5. **Compare with equal weights.** With three equally likely states it would be ln 3 = 1.10k; the Boltzmann weighting toward the ground state lowers it a little.

**Answer:** Z = 2.140, the probabilities are 0.467, 0.317 and 0.216, U = 7.48 meV and S = 1.05k.
:::
:::

::: example
## Change the three-level distribution above by ε(1, −2, 1) with ε = 0.01. Does it still have the same energy? What happens to its entropy?

::: solution
1. **Still normalized.** The change sums to zero, so the probabilities still add to 1.
2. **Energy change.** It's zero, so U stays 7.48 meV:
   $$0 \times 1 + 10 \times (-2) + 20 \times 1 = 0$$
3. **New entropy.** The new probabilities are 0.477, 0.297 and 0.226, and the entropy falls by $9.8 \times 10^{-4}k$.
4. **Quadratic estimate.** It agrees:
   $$\begin{aligned} \Delta S &\approx \frac{\varepsilon^2}{2}\Big(\frac{1}{0.467} + \frac{4}{0.317} \\ &\quad + \frac{1}{0.216}\Big) \\ &= 9.7 \times 10^{-4} \end{aligned}$$
5. **The other sign.** ε = −0.01 lowers it by the same amount to first order: the Boltzmann distribution sits at the top of the entropy hill.

**Answer:** the energy stays 7.48 meV, and the entropy falls by $9.8 \times 10^{-4}k$.
:::
:::

::: check
kind: python

## Step 1. Write `ln_multiplicity(N, n)` returning $\ln\binom{N}{n}$ with `math.lgamma`, and `gaussian_check(N, s)` returning the exact ratio $g(N, s)/g(N, 0)$ for N spins with n = N/2 + s up.

```python starter
import math

def ln_multiplicity(N, n):
    return 0.0

def gaussian_check(N, s):
    return 1.0

print(ln_multiplicity(1000, 500), gaussian_check(10000, 50))
```

```python solution
import math

def ln_multiplicity(N, n):
    return math.lgamma(N + 1) - math.lgamma(n + 1) - math.lgamma(N - n + 1)

def gaussian_check(N, s):
    return math.exp(ln_multiplicity(N, N // 2 + s) - ln_multiplicity(N, N // 2))

print(ln_multiplicity(1000, 500), gaussian_check(10000, 50))
```

```python tests
import math
assert abs(ln_multiplicity(1000, 500) - 689.4673) < 1e-3, f"ln C(1000, 500) is 689.467; got {ln_multiplicity(1000, 500)}"
assert abs(ln_multiplicity(10, 5) - math.log(252)) < 1e-9, "C(10, 5) = 252."
r = gaussian_check(10000, 50)
assert abs(r - 0.606556) < 1e-5, f"The exact ratio for N = 10000, s = 50 is 0.606556; got {r}"
assert abs(r / math.exp(-2 * 50**2 / 10000) - 1) < 1e-3, "It should match the Gaussian exp(-2s²/N) to better than 0.1%."
```

::: right
Right. The exact ratio, 0.606556, differs from the Gaussian's 0.606531 by four parts in 10⁵.
:::
:::

::: check
kind: python

## Step 2. Write `share(NA, NB, q)` returning a list of the probabilities that solid A holds $q_A$ = 0, 1, …, q quanta when two Einstein solids share q quanta. Work with logarithms of the multiplicities.

```python starter
import math

def share(NA, NB, q):
    return [1 / (q + 1)] * (q + 1)

P = share(300, 200, 100)
print(max(range(101), key=lambda a: P[a]))
```

```python solution
import math

def ln_omega(N, q):
    return math.lgamma(q + N) - math.lgamma(q + 1) - math.lgamma(N)

def share(NA, NB, q):
    logs = [ln_omega(NA, a) + ln_omega(NB, q - a) for a in range(q + 1)]
    top = max(logs)
    w = [math.exp(x - top) for x in logs]
    total = sum(w)
    return [x / total for x in w]

P = share(300, 200, 100)
print(max(range(101), key=lambda a: P[a]))
```

```python tests
import math
P = share(300, 200, 100)
assert len(P) == 101 and abs(sum(P) - 1) < 1e-12, "Return q + 1 probabilities that add to 1."
assert max(range(101), key=lambda a: P[a]) == 60, "The most probable split gives A 60 quanta."
mean = sum(a * p for a, p in enumerate(P))
sd = math.sqrt(sum((a - mean) ** 2 * p for a, p in enumerate(P)))
assert abs(sd - 5.3612) < 1e-3, f"The width is 5.361 quanta; got {sd}"
assert abs(sum(P[:51]) - 0.03949) < 1e-4, "B holds half or more about 3.9% of the time."
```

::: right
Right. Large systems behave the same way with a far narrower peak, which is why thermal equilibrium looks sharp.
:::
:::

::: check
kind: python

## Step 3. Write `thermo(E, g, T)` for levels `E` (meV) with degeneracies `g` at temperature `T` (K), returning `(Z, U, S, C)`: the partition function, the energy in meV, and the entropy and heat capacity in units of k.

```python starter
import math

def thermo(E, g, T):
    return 1.0, 0.0, 0.0, 0.0

print(thermo([0, 10, 20], [1, 1, 1], 300))
```

```python solution
import math

def thermo(E, g, T):
    kT = 0.08617333 * T
    w = [gi * math.exp(-e / kT) for e, gi in zip(E, g)]
    Z = sum(w)
    p = [x / Z for x in w]
    U = sum(pi * e for pi, e in zip(p, E))
    U2 = sum(pi * e * e for pi, e in zip(p, E))
    S = -sum(pi * math.log(pi / gi) for pi, gi in zip(p, g) if pi > 0)
    C = (U2 - U * U) / kT**2
    return Z, U, S, C

print(thermo([0, 10, 20], [1, 1, 1], 300))
```

```python tests
import math
Z, U, S, C = thermo([0, 10, 20], [1, 1, 1], 300)
assert abs(Z - 2.1405) < 1e-3 and abs(U - 7.4835) < 1e-3, f"Expected Z = 2.1405 and U = 7.4835 meV; got {Z}, {U}"
assert abs(S - 1.0505) < 1e-3, f"S should be 1.0505k; got {S}"
Z2, U2, S2, C2 = thermo([0, 50], [1, 1], 300)
x = 50 / (0.08617333 * 300)
assert abs(C2 - x * x * math.exp(x) / (math.exp(x) + 1) ** 2) < 1e-9, "A two-level system's C must match the Schottky formula."
Z3, U3, S3, C3 = thermo([0, 1e-6], [1, 3], 300)
assert abs(S3 - math.log(4)) < 1e-6, "Four nearly degenerate states give S = ln 4."
```

::: right
Right. With degeneracies included, the same few lines handle any finite set of levels.
:::
:::

::: check
kind: python

## Step 4. Write `schottky_peak(D)` returning the temperature (K) at which a two-level system with splitting `D` (meV) has its largest heat capacity. Use a golden-section search in T.

```python starter
def schottky_peak(D):
    return D / 0.08617333

print(schottky_peak(1.0))
```

```python solution
import math

def heat(D, T):
    x = D / (0.08617333 * T)
    return x * x * math.exp(x) / (math.exp(x) + 1) ** 2

def schottky_peak(D):
    a, b = 0.05 * D / 0.08617333, 5 * D / 0.08617333
    r = (math.sqrt(5) - 1) / 2
    for _ in range(200):
        c, d = b - r * (b - a), a + r * (b - a)
        if heat(D, c) > heat(D, d):
            b = d
        else:
            a = c
    return 0.5 * (a + b)

print(schottky_peak(1.0))
```

```python tests
T = schottky_peak(1.0)
assert abs(T / (0.416778 / 0.08617333) - 1) < 1e-4, f"The peak is at kT = 0.41678 Δ, 4.837 K for 1 meV; got {T}"
assert abs(schottky_peak(10.0) / T - 10) < 1e-3, "The peak temperature scales with the splitting."
```

::: right
Right. The peak sits at kT = 0.417Δ, where the heat capacity reaches 0.439k per system.
:::
:::

::: check
kind: python

## Step 5. Write `entropy_drop(E, T, eps)` for three equally spaced levels `E` (meV) at `T`: perturb the Boltzmann probabilities by eps × (1, −2, 1), which keeps both their sum and the energy fixed, and return S(Boltzmann) − S(perturbed) in units of k.

```python starter
import math

def entropy_drop(E, T, eps):
    return 0.0

print(entropy_drop([0, 10, 20], 300, 0.01))
```

```python solution
import math

def entropy_drop(E, T, eps):
    kT = 0.08617333 * T
    w = [math.exp(-e / kT) for e in E]
    Z = sum(w)
    p = [x / Z for x in w]
    q = [p[0] + eps, p[1] - 2 * eps, p[2] + eps]
    S = lambda r: -sum(x * math.log(x) for x in r)
    return S(p) - S(q)

print(entropy_drop([0, 10, 20], 300, 0.01))
```

```python tests
d1 = entropy_drop([0, 10, 20], 300, 0.01)
d2 = entropy_drop([0, 10, 20], 300, -0.01)
assert d1 > 0 and d2 > 0, "Any change at fixed energy must lower the entropy."
assert abs(d1 - 9.787e-4) < 2e-6, f"For eps = 0.01 the drop is 9.79e-4; got {d1}"
r = entropy_drop([0, 10, 20], 300, 0.002) / entropy_drop([0, 10, 20], 300, 0.001)
assert abs(r - 4) < 0.02, "For small eps the drop grows as eps squared."
```

::: right
Right. The drop is quadratic in ε: the Boltzmann distribution is a maximum of the entropy, with zero slope in every allowed direction.
:::
:::

::: check
kind: parts
given: A = 100 | 300; B = 200 | 400; q = 100 | 500

## Two Einstein solids with {A} and {B} oscillators share {q} quanta.

::: part
answer: q*A/(A + B)
tolerance: 0.5%

### How many quanta does A most probably hold?

::: misses
- [q/2] Energy divides in proportion to the number of oscillators.
- [any] $q\frac{N_A}{N_A + N_B}$.
:::
:::

::: part
answer: 1/sqrt(A/((q*A/(A + B))*(q*A/(A + B) + A)) + B/((q*B/(A + B))*(q*B/(A + B) + B)))
tolerance: 1%

### About how wide is the distribution (one standard deviation)?

::: misses
- [any] $\sigma^2 = \left[\frac{N_A}{q_A(q_A + N_A)} + \frac{N_B}{q_B(q_B + N_B)}\right]^{-1}$.
:::
:::
:::

::: check
kind: parts
given: D = 5 | 10 | 20; T = 100 | 300

## A system has levels at 0, {D} and 2 × {D} meV, one state each, at {T} K.

::: part
answer: 1 + exp(-D/(0.08617333*T)) + exp(-2*D/(0.08617333*T))
tolerance: 0.5%

### What's its partition function?

::: misses
- [any] Sum the three Boltzmann factors.
:::
:::

::: part
answer: (D*exp(-D/(0.08617333*T)) + 2*D*exp(-2*D/(0.08617333*T)))/(1 + exp(-D/(0.08617333*T)) + exp(-2*D/(0.08617333*T)))
unit: meV
tolerance: 0.5%

### What's its average energy?

::: misses
- [any] $U = \frac{1}{Z}\sum E_ie^{-E_i/kT}$.
:::
:::
:::

::: check
given: n = 0.01 | 1 | 3
answer: 0.43923*n*8.314462618
unit: J/K
tolerance: 0.5%

## A sample holds {n} mol of two-level systems. What's the largest heat capacity they can have, at the Schottky peak?

::: right
Right. The peak value is 0.439k per system, or 0.439R per mole.
:::

::: misses
- [n*8.314462618] A two-level system never reaches R per mole; it peaks at 0.439R.
- [any] $0.439nR$.
:::
:::

::: check
given: N = 10 | 1000 | 1000000
answer: 0.5*ln(2*pi*N)
tolerance: 0.5%

## By how much does N ln N − N fall short of ln N! for N = {N}, using the next term of Stirling's series?

::: right
Right. $\frac12\ln(2\pi N)$, a shortfall that grows only logarithmically.
:::

::: misses
- [ln(2*pi*N)] It's half that logarithm.
- [any] $\ln N! \approx N\ln N - N + \frac12\ln(2\pi N)$.
:::
:::

::: explain
## Why does the most probable split of energy between two large systems become, in practice, the only one you ever see?

::: model
The number of ways to make each split is a product of two huge multiplicities, and its logarithm is a sum of two entropies. Near the peak that logarithm falls off quadratically, so the distribution is a Gaussian whose width grows only as the square root of the system size, while the range of possible splits grows in proportion to the size. For 500 oscillators the width is several percent of the total, and fluctuations are easy to see; for $10^{23}$ particles the relative width is about $10^{-12}$, so every measurement finds the most probable split. That's why thermodynamic quantities like temperature and energy look perfectly definite for everyday objects.
:::
:::

::: practice

::: check
given: A = 50 | 500; B = 150 | 250; q = 200 | 800
answer: q*A/(A + B)
tolerance: 0.5%

## Most probable quanta in A: $N_A$ = {A}, $N_B$ = {B}, q = {q}?

::: misses
- [any] $q\frac{N_A}{N_A + N_B}$.
:::
:::

::: check
given: D = 4 | 12; T = 77 | 300
answer: 1 + exp(-D/(0.08617333*T)) + exp(-2*D/(0.08617333*T))
tolerance: 0.5%

## Z for levels 0, {D}, 2 × {D} meV at {T} K?

::: misses
- [any] Sum the Boltzmann factors.
:::
:::
:::
