---
title: "Thermal lab: integrals, equilibria and a Metropolis simulation"
heading: The Debye function, carrier freeze-out, and an Ising magnet at its Curie point
eyebrow: "B11 · Lesson 51 · Thermal lab"
xp: 60
---

::: hook
Most of this course's results came from formulas with a limit taken: low temperature, high temperature, nondegenerate, mean field. A computer removes the limits. In this lab you'll integrate the Debye heat capacity at every temperature, solve silicon's charge-neutrality equation exactly, freeze-out included, by bisection on the Fermi level, and simulate a ferromagnet spin by spin with the **Metropolis algorithm**, which samples microstates with Boltzmann probabilities. The simulation gets what the mean-field model of lesson 33 couldn't: the right Curie temperature for a two-dimensional magnet, checked against Onsager's exact solution.
:::

::: predict
## A Metropolis simulation flips a spin if that lowers the energy, and otherwise flips it with probability $e^{-\Delta E/kT}$. Why does that produce the Boltzmann distribution?

- [ ] It doesn't; it finds the ground state
- [x] Because it balances every pair of transitions so that each state's probability ends up proportional to $e^{-E/kT}$
- [ ] Because random numbers are uniform
- [ ] Only at high temperature

::: reveal
For any two states a and b with $E_b > E_a$, the rate a → b is $e^{-(E_b - E_a)/kT}$ and b → a is 1, so in a steady state $P_bP_{b\to a} = P_aP_{a\to b}$ gives $P_b/P_a = e^{-(E_b - E_a)/kT}$. That's **detailed balance**. The walk visits microstates with exactly the Boltzmann weights, so averages along it are thermal averages, without ever computing Z.
:::
:::

::: nameit
## What you'll write

1. `debye_C(T, theta, n=2001)`: the Debye molar heat capacity $9R\left(\frac T\Theta\right)^3\int_0^{\Theta/T}\frac{x^4e^x}{(e^x - 1)^2}dx$ by Simpson's rule on n points (start just above 0 to avoid 0/0).
2. `carriers(T, ND, Ed=0.045, Eg=1.12, Nc300=3.2e19, Nv300=1.8e19)`: return `(n, EF)` for silicon with donors $N_D$ at binding energy $E_d$, solving neutrality $N_D^+ + p = n$ exactly by bisecting on $E_F$ (measured from $E_c$, so negative in the gap). Use $n = N_ce^{E_F/kT}$, $p = N_ve^{(-E_g - E_F)/kT}$, $N_D^+ = \frac{N_D}{1 + 2e^{(E_F + E_d)/kT}}$, with $N_c, N_v \propto T^{3/2}$.
3. `ising(L, T, sweeps, seed=1)`: a 2D Ising model on an L × L periodic lattice (J = k = 1), starting all up, updated by Metropolis; return the array of |magnetization per spin| after each sweep. Updating the two checkerboard sublattices alternately, with NumPy, keeps it fast.

## What to expect

- Debye: $C/3R$ = 0.9517 at T = Θ, approaching 1 above and the $T^3$ law below.
- Silicon, $N_D = 10^{16}$: n = 0.996 × 10¹⁶ at 300 K, 5.5 × 10¹⁴ at 50 K (freeze-out), above $10^{16}$ by 700 K (intrinsic).
- Ising: Onsager's exact result $T_c = \frac{2}{\ln(1 + \sqrt2)}$ = 2.269, and below it $m = \left[1 - \sinh^{-4}(2/T)\right]^{1/8}$. Mean field (lesson 33) would put $T_c$ at 4.
:::

::: example
## How many terms does Simpson's rule need for the Debye integral to be good to 10⁻⁶?

::: solution
1. **How the error scales.** The integrand is smooth, so Simpson's error falls as $h^4$.
2. **A fine grid.** Across [0, 50] (T = Θ/50) with 2001 points, h = 0.025 and the error is far below 10⁻⁶ of the result.
3. **A coarse grid.** Even 201 points give about five digits.
4. **The point at zero.** The only care needed is at x = 0, where the integrand is 0/0 but tends smoothly to 0; starting at 10⁻⁹ avoids it.

**Answer:** 2001 points (h = 0.025) are far more than enough for 10⁻⁶, and even 201 give about five digits.
:::
:::

::: example
## Why does the Ising simulation start with all spins up?

::: solution
1. **Below $T_c$.** The two magnetized states, all up and all down, are separated by a free-energy barrier, and a small lattice started at random can get stuck in long-lived domains.
2. **Start ordered.** Starting ordered and discarding the first couple of hundred sweeps as equilibration gives a clean estimate.
3. **Above $T_c$.** The start doesn't matter: the order melts within a few sweeps.

**Answer:** an ordered start avoids long-lived domains below $T_c$, so after a couple of hundred equilibration sweeps the estimate is clean; above $T_c$ the start doesn't matter.
:::
:::

::: check
kind: python

## Step 1. Write `debye_C(T, theta, n=2001)`.

```python starter
import numpy as np
R = 8.314462618

def debye_C(T, theta, n=2001):
    xm = theta / T
    x = np.linspace(1e-9, xm, n)
    # integrand x^4 e^x / (e^x - 1)^2, Simpson's rule, then 9R (T/theta)^3 times it
    return 0.0

print(debye_C(400, 400) / (3 * R))
```

```python solution
import numpy as np
R = 8.314462618

def debye_C(T, theta, n=2001):
    xm = theta / T
    x = np.linspace(1e-9, xm, n)
    f = x**4 * np.exp(x) / np.expm1(x)**2
    h = x[1] - x[0]
    integral = h / 3 * (f[0] + f[-1] + 4 * f[1:-1:2].sum() + 2 * f[2:-1:2].sum())
    return 9 * R * (T / theta)**3 * integral

print(debye_C(400, 400) / (3 * R))
```

```python tests
import numpy as np
for t, want in ((1.0, 0.951732), (0.5, 0.825408), (0.1, 0.0758210), (10.0, 0.999500)):
    got = debye_C(t * 400, 400) / (3 * R)
    assert abs(got / want - 1) < 1e-4, f"At T = {t}Θ, C/3R should be {want}; got {got:.6f}."
low = debye_C(4, 400)
assert abs(low / (1943.77 * (4 / 400)**3) - 1) < 1e-4, "At T = Θ/100 the result should match the T³ law."
```

::: right
Right. One integral covers the whole range, from the $T^3$ law to Dulong–Petit, with 0.952 of the classical value at T = Θ.
:::
:::

::: check
kind: python

## Step 2. Write `carriers(T, ND, ...)` returning `(n, EF)`.

```python starter
import numpy as np
k = 8.617333e-5

def carriers(T, ND, Ed=0.045, Eg=1.12, Nc300=3.2e19, Nv300=1.8e19):
    kT = k * T
    Nc = Nc300 * (T / 300)**1.5
    Nv = Nv300 * (T / 300)**1.5
    # charge(EF) = ND+ + p - n; bisect EF between -Eg and 0.2 eV
    EF = -0.5 * Eg
    return Nc * np.exp(EF / kT), EF

print(carriers(300, 1e16))
```

```python solution
import numpy as np
k = 8.617333e-5

def carriers(T, ND, Ed=0.045, Eg=1.12, Nc300=3.2e19, Nv300=1.8e19):
    kT = k * T
    Nc = Nc300 * (T / 300)**1.5
    Nv = Nv300 * (T / 300)**1.5
    def charge(EF):
        n = Nc * np.exp(EF / kT)
        p = Nv * np.exp((-Eg - EF) / kT)
        NDp = ND / (1 + 2 * np.exp((EF + Ed) / kT))
        return NDp + p - n
    lo, hi = -Eg, 0.2
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if charge(mid) > 0:
            lo = mid
        else:
            hi = mid
    EF = 0.5 * (lo + hi)
    return Nc * np.exp(EF / kT), EF

print(carriers(300, 1e16))
```

```python tests
n, EF = carriers(300, 1e16)
assert abs(n / 9.96462e15 - 1) < 2e-3, f"At 300 K, 99.6% of 10^16 donors are ionized: n = 9.965e15; got {n:.4g}."
assert abs(EF + 0.208741) < 1e-3, f"E_F should be 0.209 eV below E_c; got {EF:.4f} eV."
n, EF = carriers(50, 1e16)
assert abs(n / 5.47421e14 - 1) < 1e-2, f"At 50 K the donors freeze out: n = 5.47e14; got {n:.4g}."
n, EF = carriers(700, 1e16)
assert abs(n / 1.43873e16 - 1) < 1e-2, f"At 700 K intrinsic carriers add to the donors: n = 1.44e16; got {n:.4g}."
```

::: right
Right. One equation, solved honestly, covers freeze-out at 50 K, full ionization at room temperature and intrinsic conduction at 700 K, which the textbook approximations each handle only in their own range.
:::
:::

::: check
kind: python

## Step 3. Write `ising(L, T, sweeps, seed=1)` returning |m| after each sweep.

```python starter
import numpy as np

def ising(L, T, sweeps, seed=1):
    rng = np.random.default_rng(seed)
    s = np.ones((L, L), dtype=int)
    i, j = np.indices((L, L))
    masks = [(i + j) % 2 == 0, (i + j) % 2 == 1]
    ms = []
    for sweep in range(sweeps):
        # for each sublattice: neighbor sum with np.roll, dE = 2 s nb,
        # flip where a uniform random number is below exp(-dE / T)
        ms.append(abs(s.mean()))
    return np.array(ms)

print(ising(16, 1.5, 300)[100:].mean())
```

```python solution
import numpy as np

def ising(L, T, sweeps, seed=1):
    rng = np.random.default_rng(seed)
    s = np.ones((L, L), dtype=int)
    i, j = np.indices((L, L))
    masks = [(i + j) % 2 == 0, (i + j) % 2 == 1]
    ms = []
    for sweep in range(sweeps):
        for mask in masks:
            nb = np.roll(s, 1, 0) + np.roll(s, -1, 0) + np.roll(s, 1, 1) + np.roll(s, -1, 1)
            dE = 2 * s * nb
            flip = (rng.random((L, L)) < np.exp(-dE / T)) & mask
            s[flip] *= -1
        ms.append(abs(s.mean()))
    return np.array(ms)

print(ising(16, 1.5, 300)[100:].mean())
```

```python tests
import numpy as np
onsager = lambda T: (1 - np.sinh(2 / T)**-4)**0.125
m15 = ising(16, 1.5, 600)[200:].mean()
assert abs(m15 - onsager(1.5)) < 0.01, f"At T = 1.5 the magnetization should be near Onsager's {onsager(1.5):.4f}; got {m15:.4f}."
m20 = ising(16, 2.0, 600)[200:].mean()
assert 0.85 < m20 < 0.95, f"At T = 2.0 it should be near 0.91 (Onsager), slightly lower on a 16 × 16 lattice; got {m20:.3f}."
m35 = ising(16, 3.5, 600)[200:].mean()
assert m35 < 0.25, f"Above T_c = 2.27 the order should melt; got |m| = {m35:.3f}."
```

::: right
Right. The simulated magnet stays ordered at T = 1.5 and 2.0, matching Onsager's exact curve, and melts at 3.5, between the true $T_c$ of 2.27 and nowhere near mean field's 4.
:::
:::

::: check
given: t = 1 | 1.5 | 2.1
answer: (1 - sinh(2/t)^(-4))^0.125
tolerance: 0.5%

## What's Onsager's exact magnetization of the 2D Ising model at T = {t} (in units of J/k)?

::: right
Right. $\left[1 - \sinh^{-4}(2/T)\right]^{1/8}$ = {answer}.
:::

::: misses
- [sqrt(3*(1 - t/4))] That's the mean-field estimate, with $T_c$ = 4.
- [any] Not yet. Onsager's formula.
:::
:::

::: check
given: d = 0.5 | 1 | 2; T = 1 | 2.5
answer: exp(-4*d/T)
tolerance: 0.5%

## In a Metropolis step, flipping a spin would raise the energy by 4 × {d} J. At T = {T} J/k, with what probability is it accepted?

::: right
Right. $e^{-\Delta E/kT}$ = {answer}.
:::

::: misses
- [exp(-2*d/T)] Use the full energy change, 4 × {d}.
- [any] Not yet. Accept with probability $e^{-\Delta E/kT}$.
:::
:::

::: check
given: L = 8 | 16 | 32; s = 500 | 2000
answer: L^2*s
tolerance: 0

## How many single-spin updates does a {s}-sweep Metropolis run on an {L} × {L} lattice perform?

::: right
Right. $L^2$ per sweep: {answer}.
:::

::: misses
- [L*s] A sweep visits every one of the $L^2$ spins.
- [any] Not yet. One sweep = one attempted update per spin.
:::
:::

::: explain
## Why does the mean-field model predict a Curie temperature of 4 for the 2D Ising model when the true value is 2.27?

::: model
Mean field replaces each spin's four neighbors by their average magnetization, ignoring the fact that the neighbors themselves fluctuate and are correlated with the spin in question. In two dimensions those fluctuations are large: as the temperature rises, the system breaks into domains and flipped clusters that destroy long-range order well before the average field would vanish. By pretending every spin feels a steady, perfectly ordered field, mean field overestimates how robust the order is, and so overestimates $T_c$. The Metropolis simulation includes every fluctuation exactly, because it samples real configurations, and it lands on Onsager's exact value.
:::
:::

::: practice

::: check
given: t = 0.5 | 1 | 1.2 | 1.5 | 2 | 2.2
answer: (1 - sinh(2/t)^(-4))^0.125
tolerance: 0.5%

## Onsager magnetization at T = {t}?

::: misses
- [any] $[1 - \sinh^{-4}(2/T)]^{1/8}$.
:::
:::

::: check
given: d = 0.25 | 3; T = 0.8 | 4
answer: exp(-4*d/T)
tolerance: 0.5%

## Acceptance for ΔE = 4 × {d} at T = {T}?

::: misses
- [any] $e^{-\Delta E/kT}$.
:::
:::

::: check
given: L = 10 | 64; s = 100 | 5000
answer: L^2*s
tolerance: 0

## Updates in {s} sweeps of {L} × {L}?

::: misses
- [any] $L^2$ per sweep.
:::
:::
:::
