Computational physics turns a physical question into a result that can be calculated, tested, and interpreted. Getting a program to print a number is an intermediate step. We also need to know which model it solves, where its errors come from, and whether its conclusions survive changes in numerical parameters.

This tutorial starts with the way a computer stores numbers and builds toward quantum problems, particle simulation, and stochastic processes. It assumes calculus and elementary linear algebra; probability, algorithms, and programming concepts are introduced as needed. A month can establish a coherent working framework and lead to a small, independently verified project. Model selection and performance optimization for complex systems develop further through research practice.

中文版 · Download English Markdown · Download the Python laboratory

Knowledge map and how to study

StageQuestionChapters
Establish a computational languageHow does a number enter a computer? What does error mean?1. Computing, 2. Error
Learn the basic operatorsHow do we integrate, sample, and differentiate?3. Quadrature, 4. MC integration, 5. Differentiation
Solve evolution and boundary problemsHow do we compute trajectories, temperature fields, waves, and eigenstates?6. ODEs, 7. Boundary problems, 8. PDEs, 9. Matrices
Enter quantum materialsHow do periodicity and interfaces affect a wavefunction?10. Plane waves, 11. Transfer matrices
Simulate many particlesHow do we construct, advance, and analyze an atomic system?12. MD models, 13. Ensembles, 14. Analysis
Connect probability and dynamicsHow do we sample equilibrium? How do we model rare events?15. Markov chains, 16. Ising, 17. KMC
Produce a research resultHow do we fit, validate, organize study, and read further?18. Research workflow, 19. Thirty days, 20. Source map

On a first pass, run each experiment and return to its derivation. On a second pass, explain how each algorithm can fail. The examples require Python 3.10 or later; the core laboratory depends only on NumPy. In a terminal, run:

python -m venv .venv
# Windows PowerShell:
.venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate
python -m pip install numpy
python computational_physics_lab.py

If PowerShell blocks activation, run .venv\Scripts\python.exe -m pip install numpy, then use that interpreter to run the file. Keep the downloaded laboratory beside your own scripts and import it with import computational_physics_lab as lab. These are original teaching implementations with documented assumptions and analytical checks. For large research calculations, use established numerical libraries after understanding those assumptions.

1. From a physical model to a computer program

1.1 Begin with an observable

Suppose you want to study a cooling rod. A precise question might be “When does its center reach a specified temperature?” rather than simply “Solve the heat equation.” Identify the observable, then choose the model: can transverse temperature differences be neglected, is conductivity constant, and are the ends held at fixed temperature or insulated? Only then choose a grid and an algorithm.

The complete chain is physical assumptions → equations and initial/boundary conditions → discretization → program → verification → physical interpretation . One equation admits several algorithms; one algorithm can solve many physical problems. Diffusion, random walks, and particle dynamics will describe transport from different viewpoints. Their connections matter more than memorizing isolated formulas.

1.2 Bits, memory, and processors

A bit represents either 0 or 1; eight bits make a byte. Memory can be viewed as a sequence of addressed bytes. A language and its runtime associate a variable name with an object or storage location. The processor executes instructions that fetch, calculate, store, compare, and jump. A loop repeats operations until its condition stops being satisfied.

A compiler translates source code into executable instructions. Python usually executes bytecode through an interpreter, but many NumPy operations call compiled numerical kernels. A NumPy matrix multiplication is therefore not generally interpreted element by element in Python. Choosing the right algorithm and measuring the actual bottleneck is often more useful than immediately switching languages.

An array has a shape, an element type, and memory strides. An array of NN float64 values requires approximately 8N8N bytes for its data alone. A dense 104×10410^4\times10^4 matrix occupies about 0.8 GB, with additional workspace needed for factorization. Doubling resolution in every direction of a three-dimensional grid multiplies storage by eight.

1.3 A minimum programming vocabulary

import numpy as np

def acceleration(x, omega=1.0):
    return -omega**2 * x

x = np.array([1.0, 0.0, -1.0])
v = np.zeros_like(x)
dt = 0.01
for step in range(100):
    v = v + dt * acceleration(x)
    x = x + dt * v
print(x)

def defines a function, return returns a result, and indentation defines a block. range(100) gives integers from 0 through 99. ** means exponentiation, = assigns, and == compares. Array indices start at zero. This code advances three uncoupled oscillators at once. Updating velocity before position makes it the Euler–Cromer method introduced later.

x * y multiplies elementwise; A @ x performs matrix multiplication. x[:, None] gives a one-dimensional array a column shape, enabling broadcasting into two-dimensional calculations. Slices may share memory: saved = x does not preserve an independent snapshot; use saved = x.copy() when needed. Saved data columns also need definitions, such as time, position, velocity, including their units.

1.4 Scales, units, and cost

For mx¨=−kxm\ddot x=-kx, set x=Lqx=Lq and t=m/k τt=\sqrt{m/k}\,\tau to obtain q′′=−qq''=-q. Nondimensionalization reduces the number of parameters and helps prevent very different length, time, and energy scales from confusing error control. Retain the conversion factors so that results can be compared with measurements.

O(N)O(N) means that work grows approximately linearly with problem size, not that a calculation takes a particular number of seconds. Evaluating every particle pair usually costs O(N2)O(N^2); a dense linear solve commonly costs O(N3)O(N^3). Replacing a quadratic algorithm with a linear one usually matters more than making a loop twice as fast.

Experiment: change the initial positions to [1, 2, 3] and check proportionality of the responses. Print x.dtype, x.shape, and x.nbytes. Explain how replacing x.copy() by x could corrupt stored trajectory history.

2. Error: printed digits are not necessarily trustworthy digits

2.1 Floating-point numbers form a finite set

A computer cannot store arbitrary real numbers exactly. An IEEE 754 binary64 number has one sign bit, eleven exponent bits, and 52 explicit fraction bits. A normal number has the form

x=(−1)s(1.f)2 2ex=(-1)^s(1.f)_2\,2^e

The implicit leading 1 gives 53 significant binary digits, roughly 15–16 decimal digits. Adjacent representable values near 1 are separated by ϵ=2−52≈2.22×10−16\epsilon=2^{-52}\approx2.22\times10^{-16}. For rounding to nearest, the usual unit roundoff is u=2−53u=2^{-53}. The smallest positive normal number is 2−10222^{-1022}; subnormal values extend to 2−10742^{-1074}, with decreasing relative precision near zero. An all-ones exponent represents infinity when the fraction is zero and NaN when it is nonzero.

Decimal 0.1 repeats indefinitely in binary, so 0.1 + 0.2 == 0.3 is usually false. Compare computed quantities using physically meaningful absolute and relative tolerances:

∣a−b∣≤atol+rtol∣b∣|a-b|\le \mathrm{atol}+\mathrm{rtol}|b|

Absolute tolerance becomes especially important near b=0b=0. Ordinary Python integers have extensible precision; fixed-width NumPy integers can overflow. They are different numerical types.

2.2 Five distinct sources of error

SourceExampleResponse
Model errorClassical nuclei for low-temperature hydrogenImprove the physics; compare with experiments or a higher-level model
Parameter uncertaintyUncertain potential parameters or diffusivitySensitivity analysis and uncertainty propagation
Truncation/discretizationA finite difference replaces a derivativeConverge grids, time steps, and basis cutoffs
RoundoffSubtracting nearby large numbers; long sumsStable reformulation, suitable precision, careful summation
Statistical errorFinite MC samples or MD trajectoriesCorrelation analysis, independent runs, confidence intervals

A longer trajectory does not repair an incorrect force model. A finer grid does not remove uncertainty in an input parameter. A research report should discuss the dominant sources separately.

2.3 Cancellation, conditioning, and stability

For small xx, computing 1+x−1\sqrt{1+x}-1 subtracts nearly equal numbers and can lose most significant digits. The equivalent expression

1+x−1=x1+x+1\sqrt{1+x}-1=\frac{x}{\sqrt{1+x}+1}

avoids this cancellation. Similarly, use np.expm1(x) for ex−1e^x-1 and np.log1p(x) for log⁡(1+x)\log(1+x) when appropriate.

Conditioning describes how sensitive the mathematical problem is to input perturbations. Stability describes how an algorithm amplifies additional errors. For y=f(x)y=f(x), a local relative condition number is κ=∣xf′(x)/f(x)∣\kappa=|xf'(x)/f(x)|. Large κ\kappa means even a stable algorithm cannot recover high-accuracy answers from low-accuracy inputs.

For Ax=bAx=b, the residual is r=b−Ax^r=b-A\hat x. A small residual means the approximate solution nearly satisfies the equations. If AA is ill-conditioned, x^\hat x can nevertheless be far from the true solution. The matrix condition number κ(A)=∥A∥∥A−1∥\kappa(A)=\|A\|\|A^{-1}\| connects these statements. Numerical Recipes §1.1 illustrates instability with a recurrence: tiny roundoff contamination in a growing mode can overwhelm a desired decaying solution. The same mechanism reappears in quantum shooting and transfer matrices.

2.4 Test a program through convergence order

If an observable satisfies Q(h)=Q∗+Chp+⋯Q(h)=Q_*+Ch^p+\cdots, halving the step should reduce the leading error by approximately 2p2^p. Without an analytical answer, estimate

pobs=log⁡2∣Q(h)−Q(h/2)Q(h/2)−Q(h/4)∣p_{\rm obs}=\log_2\left|\frac{Q(h)-Q(h/2)}{Q(h/2)-Q(h/4)}\right|

All three calculations must lie in the same asymptotic regime, without dominant statistical noise, roundoff, or accidental error cancellation. Two similar answers do not establish convergence. The extrapolation

Q∗≈Q(h/2)+Q(h/2)−Q(h)2p−1Q_*\approx Q(h/2)+\frac{Q(h/2)-Q(h)}{2^p-1}

cancels a leading error term; it is not an independent exact solution.

Experiment: compare the two square-root expressions at x=10−8,10−12,10−16x=10^{-8},10^{-12},10^{-16}. Explain why algebraic equivalence does not imply equivalence in floating-point arithmetic.

3. Numerical integration: from areas to error control

The integral I=∫abf(x) dxI=\int_a^b f(x)\,dx accumulates infinitely many thin strips. Quadrature replaces that limit with a finite set of function evaluations. Let xi=a+ihx_i=a+ih and h=(b−a)/nh=(b-a)/n.

3.1 Rectangles, trapezoids, and Simpson’s rule

The left rectangle rule h∑i=0n−1f(xi)h\sum_{i=0}^{n-1}f(x_i) is generally first order globally. The midpoint rule h∑if(xi+h/2)h\sum_i f(x_i+h/2) is second order for sufficiently smooth functions. The composite trapezoid rule is

Th=h[f(a)+f(b)2+∑i=1n−1f(xi)]T_h=h\left[\frac{f(a)+f(b)}2+\sum_{i=1}^{n-1}f(x_i)\right]

Replacing a curve by a line on one interval produces an integration error of O(h3)O(h^3). There are approximately 1/h1/h intervals, giving O(h2)O(h^2) global error. Simpson’s rule integrates a quadratic interpolant over each pair of intervals and requires even nn:

Sh=h3[f0+fn+4∑i oddfi+2∑i=2,4,…,n−2fi]S_h=\frac h3\left[f_0+f_n+4\sum_{i\ \mathrm{odd}}f_i+2\sum_{i=2,4,\ldots,n-2}f_i\right]

It is fourth order globally with adequate smoothness, and exact for polynomials through degree three. These error orders assume suitable smoothness and grids; corners and singularities can change them.

import numpy as np
import computational_physics_lab as lab

exact = np.e - 1
for n in (10, 20, 40, 80):
    T = lab.trapezoid(np.exp, 0, 1, n)
    S = lab.simpson(np.exp, 0, 1, n)
    print(n, abs(T-exact), abs(S-exact))

For exe^x on [0,1][0,1], the error ratios between 20 and 40 intervals are approximately 3.9999 and 15.9964. These ratios are more informative than many printed decimal places from a single run.

3.2 Extrapolation and adaptivity

The trapezoid error often expands in h2,h4,…h^2,h^4,\ldots. Thus (4Th/2−Th)/3(4T_{h/2}-T_h)/3 removes the quadratic term; repeated extrapolation gives Romberg integration. Endpoint nonsmoothness can invalidate this even-power expansion.

Adaptive Simpson integration compares one-interval result SS with the sum S2S_2 on two halves, estimating the finer result’s error by ∣S2−S∣/15|S_2-S|/15. Subdivide again when that exceeds the allocated tolerance. A practical implementation needs a maximum recursion depth, a minimum interval width, and explicit failure reporting.

Numerical Recipes §4.7 emphasizes a fundamental limitation: finitely many sampled points can miss an arbitrarily narrow peak. An adaptive error estimate still depends on the function’s structure. Split the domain at known singularities, discontinuities, or narrow peaks. Use absolute tolerance when the integral is near zero.

3.3 Gaussian quadrature and substitutions

Gauss–Legendre quadrature chooses both nodes and weights; nn nodes integrate polynomials through degree 2n−12n-1 exactly. It is attractive for smooth functions with expensive evaluations, but is not universally better than a uniform grid.

For ∫01x−1/2 dx\int_0^1x^{-1/2}\,dx, evaluating the integrand at zero is impossible. Substitute x=t2x=t^2 and include the Jacobian dx=2t dtdx=2t\,dt. The transformed integrand is the constant 2. A substitution should improve smoothness or concentrate evaluations where needed; omitting its Jacobian changes the problem.

3.4 Multiple integrals and dimensionality

Two-dimensional trapezoid weights are products of one-dimensional weights: 1 at interior points, 1/2 along edges away from corners, and 1/4 at corners. A useful benchmark is

∫01∫01xye−x2y dx dy=12e\int_0^1\int_0^1xy e^{-x^2y}\,dx\,dy=\frac1{2e}

The laboratory function trap2d gives approximately 0.18393790 with 200 intervals per direction, compared with the exact 0.18393972. Integrating over xx first provides a short analytical check.

A hundred points per direction requires 10610^6 evaluations in three dimensions and 102010^{20} in ten. This motivates Monte Carlo integration. Experiment: compare trapezoid, Simpson, and Gaussian quadrature at equal evaluation counts; then replace the integrand by ∣x−0.3∣|x-0.3| and examine what happens to the advantage of high order.

4. Monte Carlo integration: rewrite an area as an expectation

4.1 Probability language and error bars

A random variable XX denotes a sampled outcome. Its probability density satisfies p(x)≥0p(x)\ge0 and ∫p(x)dx=1\int p(x)dx=1. The expectation E[g(X)]=∫g(x)p(x)dx\mathbb E[g(X)]=\int g(x)p(x)dx is the target of repeated sample averaging. The variance Var⁡(g)=E[(g−Eg)2]\operatorname{Var}(g)=\mathbb E[(g-\mathbb E g)^2] describes the scatter of individual outcomes.

Draw NN independent uniform points from [a,b][a,b]. Then

I^=(b−a)fˉ,SE^(I^)=(b−a)sfN,sf2=1N−1∑i(fi−fˉ)2\hat I=(b-a)\bar f,\qquad \widehat{\mathrm{SE}}(\hat I)=(b-a)\frac{s_f}{\sqrt N},\qquad s_f^2=\frac1{N-1}\sum_i(f_i-\bar f)^2

The standard deviation sfs_f describes individual samples; the standard error SE describes uncertainty in the estimated mean. With finite variance and appropriate independence assumptions, the central limit theorem supports an approximate interval I^±1.96 SE\hat I\pm1.96\,\mathrm{SE}. Its 95% coverage concerns repetitions of the experiment; one realization is not guaranteed to cover the exact answer.

Typical MC error decreases as N−1/2N^{-1/2}, so reducing it tenfold requires roughly a hundred times as many samples. The exponent does not explicitly depend on dimension, but variance, effective volume, and evaluation cost can still deteriorate with dimension. Suitability for high-dimensional integrals does not remove every high-dimensional difficulty.

4.2 Pseudorandom numbers and sampling

A pseudorandom generator evolves a deterministic internal state. A seed makes an experiment reproducible; do not repeatedly reseed inside a loop. Use np.random.default_rng(seed) and record the generator and software version. Parallel tasks should use reliable independent substreams, for example through SeedSequence.spawn, instead of copying the same state.

Common sampling methods include inverse distribution sampling, X=F−1(U)X=F^{-1}(U); rejection sampling from an easily sampled envelope; and transformations, such as converting uniform values into normal values. Exponential waiting times can be generated by −log⁡U/λ-\log U/\lambda with U∈(0,1)U\in(0,1). Implementations must handle endpoints; the laboratory uses -np.log1p(-rng.random()) / rate.

4.3 Why importance sampling works

Choose a normalized density p(x)p(x) that is positive wherever f(x)≠0f(x)\ne0. Then

I=Ep[f(X)p(X)],Var⁡(I^)=1N[∫f(x)2p(x)dx−I2]I=\mathbb E_p\left[\frac{f(X)}{p(X)}\right],\qquad \operatorname{Var}(\hat I)=\frac1N\left[\int\frac{f(x)^2}{p(x)}dx-I^2\right]

Uniform sampling wastes work when most of the contribution comes from a small region. Choosing pp close to ∣f∣|f| can reduce variance. The ideal p∝∣f∣p\propto|f| generally depends on an unknown normalization, so a practical method uses a sampleable approximation. Inspect the tails of the weights: a few enormous weights can dominate an estimate.

For f(x)=e−xf(x)=e^{-x} on [0,1][0,1], knowing the normalization lets us construct an exactly matched density with constant weights. This illustrates zero variance, but does not independently solve the unknown integral.

Stratification estimates separate subregions and combines their weighted results. Control variates exploit a correlated function with a known integral. Low-discrepancy sequences such as Sobol sequences belong to quasi-Monte Carlo and have different error theory. An iid standard error does not apply directly to a deterministic sequence; independently randomized quasi-MC replicates can support uncertainty estimation.

Experiment: lab.mc_integral() with its fixed seed gives approximately 0.63167±0.000570.63167\pm0.00057, where the uncertainty is one standard error. The exact answer is 1−e−1≈0.632121-e^{-1}\approx0.63212. Use independent seeds to compare root-mean-square error at N=103,104,105N=10^3,10^4,10^5. Do not expect every individual sequence of estimates to improve monotonically.

5. Numerical differentiation: a smaller step can be worse

Taylor expansion expresses a nearby function value as

f(x+h)=f(x)+hf′(x)+h22f′′(x)+h36f′′′(x)+⋯f(x+h)=f(x)+hf'(x)+\frac{h^2}{2}f''(x)+\frac{h^3}{6}f'''(x)+\cdots

The forward difference [f(x+h)−f(x)]/h[f(x+h)-f(x)]/h has O(h)O(h) truncation error. Subtracting expansions at positive and negative steps cancels even powers and gives

Dhf=f(x+h)−f(x−h)2h=f′(x)+h26f′′′(x)+O(h4)D_hf=\frac{f(x+h)-f(x-h)}{2h}=f'(x)+\frac{h^2}{6}f'''(x)+O(h^4)

Adding them produces a second derivative:

Dh2f=f(x+h)−2f(x)+f(x−h)h2=f′′(x)+O(h2)D_h^2f=\frac{f(x+h)-2f(x)+f(x-h)}{h^2}=f''(x)+O(h^2)

However, the first centered difference divides function-value errors by hh. Its total error often behaves like Ah2+Bϵ/hAh^2+B\epsilon/h. Balancing the terms gives an optimal scale h∼ϵ1/3h\sim\epsilon^{1/3}. For the centered second derivative, Ah2+Bϵ/h2Ah^2+B\epsilon/h^2 gives h∼ϵ1/4h\sim\epsilon^{1/4}. These are scale estimates for suitably nondimensionalized smooth functions, not universal step sizes.

import numpy as np
for h in 10.0**(-np.arange(1, 16)):
    estimate = (np.sin(1+h)-np.sin(1-h))/(2*h)
    print(h, abs(estimate-np.cos(1)))

The error usually decreases and then increases. Richardson extrapolation, (4Dh/2−Dh)/3(4D_{h/2}-D_h)/3, cancels the leading truncation term but can amplify noise. Numerical Recipes §5.7 develops adaptive extrapolation and distinguishes a smooth function that can be evaluated freely from noisy measured data.

Differencing noisy data turns noise into spikes. Locally fitting a low-degree polynomial before differentiation, as in a Savitzky–Golay method, can help; an overly broad window also erases real structure. If a function accepts complex inputs and is analytic, the complex-step approximation Im⁡f(x+ih)/h\operatorname{Im}f(x+ih)/h avoids real-number subtraction. Absolute values, branch switches, and code that discards imaginary parts can invalidate it. Automatic differentiation applies the chain rule to a program’s operations, but cannot repair an incorrect physical model.

Research application: atomic forces should satisfy F=−∇U\mathbf F=-\nabla U. Verify them with a range of finite-difference steps and look for a stable error region, rather than relying on one extremely small step.

6. Ordinary differential equations: evolving a system in time

6.1 Initial values and state vectors

An initial value problem specifies y˙=f(t,y)\dot{\mathbf y}=\mathbf f(t,\mathbf y) and y(t0)=y0\mathbf y(t_0)=\mathbf y_0. Newton’s second-order equation can be rewritten as a first-order system:

y=(xv),y˙=(vF(x,v,t)/m)\mathbf y=\begin{pmatrix}x\\v\end{pmatrix},\qquad \dot{\mathbf y}=\begin{pmatrix}v\\F(x,v,t)/m\end{pmatrix}

At a given position and velocity, the right-hand side describes the instantaneous direction of change. An integrator accumulates these local changes into a trajectory. Local existence and uniqueness commonly require continuity and suitable local Lipschitz conditions in the state. This is a different question from uniqueness of a root of an algebraic equation.

6.2 Euler, Euler–Cromer, and Verlet

Explicit Euler is yn+1=yn+hf(tn,yn)\mathbf y_{n+1}=\mathbf y_n+h\mathbf f(t_n,\mathbf y_n). Its local one-step error is O(h2)O(h^2); its global error over a fixed time interval is usually O(h)O(h). For the dimensionless harmonic oscillator,

xn+1=xn+hvn,vn+1=vn−hxn,En+1=(1+h2)Enx_{n+1}=x_n+hv_n,\quad v_{n+1}=v_n-hx_n,\quad E_{n+1}=(1+h^2)E_n

It systematically adds energy to a physically stable oscillator. Euler–Cromer updates velocity first, then uses the new velocity to update position. This improves long-time oscillatory behavior, but the method is generally still first order.

For position-dependent acceleration, velocity Verlet is

vn+1/2=vn+h2a(xn),xn+1=xn+hvn+1/2,vn+1=vn+1/2+h2a(xn+1).\begin{aligned} v_{n+1/2}&=v_n+\frac h2a(x_n),\\ x_{n+1}&=x_n+hv_{n+1/2},\\ v_{n+1}&=v_{n+1/2}+\frac h2a(x_{n+1}). \end{aligned}

It is globally second order. The position recurrence xn+1−2xn+xn−1=h2a(xn)x_{n+1}-2x_n+x_{n-1}=h^2a(x_n) has an O(h4)O(h^4) residual, which does not make the trajectory fourth order. For suitable separable Hamiltonian systems, fixed-step Verlet is symplectic and time reversible, often showing bounded energy oscillations rather than exact conservation of the original energy. Harmonic-oscillator linear stability requires hω<2h\omega<2; stability alone does not ensure accurate phase.

6.3 RK2, RK4, and adaptive control

Midpoint RK2 predicts a half-step state, then uses its slope for a full step. Classical RK4 uses four slopes; the kik_i below do not include the step size:

k1=f(tn,yn),k2=f(tn+h/2,yn+hk1/2),k3=f(tn+h/2,yn+hk2/2),k4=f(tn+h,yn+hk3),yn+1=yn+h6(k1+2k2+2k3+k4).\begin{aligned} k_1&=f(t_n,y_n),& k_2&=f(t_n+h/2,y_n+hk_1/2),\\ k_3&=f(t_n+h/2,y_n+hk_2/2),& k_4&=f(t_n+h,y_n+hk_3),\\ y_{n+1}&=y_n+\frac h6(k_1+2k_2+2k_3+k_4). \end{aligned}

For sufficiently smooth problems, the local error is fifth order and the global error fourth order. Four evaluations per step also have a cost; compare both accuracy and computing time.

Numerical Recipes §17.2 extends fixed-step advancement to adaptive integration. Two formulas of different orders share stages and estimate a local error eie_i. Define

si=atoli+rtolmax⁡(∣yn,i∣,∣yn+1,i∣),err=1d∑i(ei/si)2s_i=\mathrm{atol}_i+\mathrm{rtol}\max(|y_{n,i}|,|y_{n+1,i}|),\qquad \mathrm{err}=\sqrt{\frac1d\sum_i(e_i/s_i)^2}

For an embedded estimator scaling as h5h^5, a candidate next step is approximately 0.9h err−1/50.9h\,\mathrm{err}^{-1/5}, with limits on growth and shrinkage. Reject and recompute a step that fails the tolerance test; do not append it to the accepted trajectory. Local tolerance is not the final observable’s error, so repeat calculations with tighter tolerances.

6.4 Stiffness means more than rapid variation

For y′=−λyy'=-\lambda y, Euler’s amplification factor is 1−hλ1-h\lambda, requiring 0<hλ<20<h\lambda<2. In a system with fast and slow decaying modes, the fast mode may have become negligible, yet stability still forces an explicit method to take tiny steps. This is a characteristic stiff problem.

Backward Euler gives yn+1=yn/(1+hλ)y_{n+1}=y_n/(1+h\lambda), stable for every positive step in this decay problem. Large steps still fail to resolve the early transient accurately. Implicit Radau or BDF methods are useful research tools; supplying a Jacobian or sparsity structure can help. Numerical Recipes §17.5 explains the need for such methods.

6.5 Satellites, damping, and chaos

A satellite model can begin with gravity −GMmr/r3-GMm\mathbf r/r^3, then add drag −Cρ(h)∣vrel∣vrel-C\rho(h)|\mathbf v_{\rm rel}|\mathbf v_{\rm rel} and braking over a finite interval. Atmospheric density, velocity relative to the atmosphere, and braking times are physical inputs. First recover circular speed GM/r\sqrt{GM/r} without drag, checking energy and angular momentum. Add complexity one term at a time. Ground impact is an event: locate r−R=0r-R=0 instead of integrating through the Earth. Split integration at nonsmooth force-switching times.

A driven damped pendulum satisfies

θ¨=−ω02sin⁡θ−γθ˙+Asin⁡(Ωt)\ddot\theta=-\omega_0^2\sin\theta-\gamma\dot\theta+A\sin(\Omega t)

Start by verifying the small-angle, undriven limit. Discard transients, inspect phase space, and sample a Poincaré section once per forcing period 2π/Ω2\pi/\Omega. Periodic trajectories give finitely many points; a chaotic attractor has more complex structure. Nearby trajectories can separate because of physical chaos or numerical instability. Check step convergence, statistical observables, and finite-time Lyapunov growth instead of diagnosing chaos from an irregular-looking curve alone.

Experiment: compare euler, cromer, verlet, and rk4 with lab.oscillator(method, dt, duration). Measure convergence order using short-time endpoint errors; inspect both energy and phase over long times. Smaller short-time RK4 error does not automatically make it the best choice for every long Hamiltonian trajectory.

7. Roots, boundary value problems, and quantum shooting

7.1 Root finding needs a bracket and physical judgment

A continuous function with f(a)f(b)<0f(a)f(b)<0 has at least one root in [a,b][a,b]. Bisection halves the bracket at every iteration. Continuity is essential: crossing the pole of 1/x1/x changes sign without crossing a root. An even-multiplicity root such as (x−1)2(x-1)^2 does not change sign and can be missed by sign scanning.

Newton’s method,

xn+1=xn−f(xn)f′(xn)x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}

is fast near a simple root with a suitable initial guess and nonzero derivative, but can leave the physical domain or diverge. The secant method replaces the derivative by a difference quotient. Brent’s method combines bracketing reliability with interpolation speed, making it a useful default for many one-dimensional research problems. Examine bracket width, residual, and physical scale when stopping.

lab.bisect(lambda x: np.cos(x)-x, 0, 1) gives approximately 0.73908513325. Checking for finite function values in code does not prove continuity throughout a bracket.

7.2 Shooting turns boundary conditions into residuals

Suppose y(a)=Ay(a)=A and y(b)=By(b)=B are known but y′(a)y'(a) is not. Set the initial slope to ss, integrate, and define R(s)=y(b;s)−BR(s)=y(b;s)-B. Solve R(s)=0R(s)=0. With several unknown starting parameters, the residual becomes a vector and requires a coupled root solve.

For y′′=−1y''=-1 with y(0)=y(1)=0y(0)=y(1)=0, the exact solution is y=x(1−x)/2y=x(1-x)/2 and the initial slope is 1/2. Verify a shooting implementation on this example before attempting nonlinear boundaries. For an inhomogeneous linear equation, arbitrary linear combinations of solutions generally do not solve the same equation; an affine combination with coefficients summing to one preserves its forcing.

7.3 Schrödinger’s equation and Numerov integration

The stationary one-dimensional equation

−ℏ22mψ′′+Vψ=Eψ-\frac{\hbar^2}{2m}\psi''+V\psi=E\psi

becomes ψ′′=−q(x)ψ\psi''=-q(x)\psi with q=2m(E−V)/ℏ2q=2m(E-V)/\hbar^2. Energy is adjusted until both boundaries are satisfied. For an infinite well on 0<x<L0<x<L,

En=ℏ2π2n22mL2,ψn=2/Lsin⁡(nπx/L),n=1,2,…E_n=\frac{\hbar^2\pi^2n^2}{2mL^2},\qquad \psi_n=\sqrt{2/L}\sin(n\pi x/L),\quad n=1,2,\ldots

For the more general equation y′′=−q(x)y+s(x)y''=-q(x)y+s(x), the uniform-grid Numerov recurrence is

(1+h2qj+112)yj+1=2(1−5h2qj12)yj−(1+h2qj−112)yj−1+h212(sj+1+10sj+sj−1).\begin{aligned} \left(1+\frac{h^2q_{j+1}}{12}\right)y_{j+1} ={}&2\left(1-\frac{5h^2q_j}{12}\right)y_j -\left(1+\frac{h^2q_{j-1}}{12}\right)y_{j-1}\\ &+\frac{h^2}{12}(s_{j+1}+10s_j+s_{j-1}). \end{aligned}

It uses the differential equation to eliminate higher derivatives from a Taylor expansion. The common description “sixth order” refers to the O(h6)O(h^6) recurrence residual before division by h2h^2. Solution or eigenvalue convergence also depends on accumulation, initialization, and boundary treatment; common setups are fourth order. The laboratory’s numerov implements the homogeneous case with two caller-supplied starting values. Low-accuracy initialization can spoil an otherwise accurate recurrence.

7.4 Why integrate from both ends?

In a forbidden region, V>EV>E, solutions contain growing and decaying exponentials. Even when the desired solution decays, roundoff introduces a growing component that can eventually dominate. Integrating inward from both boundaries and matching function values and derivatives shortens this unstable propagation. For a homogeneous eigenproblem, a suitable residual is the Wronskian

W(E)=ψL(xm)ψR′(xm)−ψL′(xm)ψR(xm)=0W(E)=\psi_L(x_m)\psi_R'(x_m)-\psi_L'(x_m)\psi_R(x_m)=0

This avoids division by a wavefunction at its nodes. Rescale when necessary to prevent overflow, and verify that changing the matching point leaves eigenvalues unchanged within error. Numerical Recipes §§18.1–18.3 extend simple shooting to multiple constraints, matching, and global relaxation.

Truncating an infinite domain to [−L,L][-L,L] introduces two separate errors: a coarse mesh and a small computational box. Refine hh at fixed box size, then enlarge the box at sufficiently fine fixed spacing. Check normalization, node counts, parity, and orthogonality. Experiment: find the first three infinite-well energies using root finding plus Numerov, then cross-check with the matrix method in Chapter 9.

8. Partial differential equations: stability, conservation, and boundaries

8.1 Identify the equation’s character

Diffusion equations are parabolic and describe smoothing and dissipation. Wave equations are hyperbolic and describe propagation at finite speed. Poisson equations are elliptic and describe fields subject to global boundary constraints. Dirichlet conditions specify values, Neumann conditions specify normal derivatives, and periodic conditions connect opposite boundaries. Missing conditions can make a discrete matrix singular. A pure Neumann Poisson problem also needs a compatibility condition and a choice fixing its arbitrary additive constant.

8.2 Explicit diffusion

For ut=Duxxu_t=Du_{xx} on xj=jΔxx_j=j\Delta x, tn=nΔtt_n=n\Delta t,

ujn+1=ujn+r(uj+1n−2ujn+uj−1n),r=DΔtΔx2u_j^{n+1}=u_j^n+r(u_{j+1}^n-2u_j^n+u_{j-1}^n),\qquad r=\frac{D\Delta t}{\Delta x^2}

Substituting a Fourier error mode eikjΔxe^{ikj\Delta x} gives amplification factor G=1−4rsin⁡2(kΔx/2)G=1-4r\sin^2(k\Delta x/2). Requiring ∣G∣≤1|G|\le1 for every mode gives r≤1/2r\le1/2 in one dimension. On a multidimensional rectangular grid, require ∑αDΔt/Δxα2≤1/2\sum_\alpha D\Delta t/\Delta x_\alpha^2\le1/2. Halving spatial spacing usually requires quartering an explicit time step.

8.3 Implicit diffusion and Crank–Nicolson

Backward Euler evaluates spatial derivatives at the new time and solves a tridiagonal system at every step. Crank–Nicolson (CN) averages old and new times:

−r2uj−1n+1+(1+r)ujn+1−r2uj+1n+1=r2uj−1n+(1−r)ujn+r2uj+1n-\frac r2u_{j-1}^{n+1}+(1+r)u_j^{n+1}-\frac r2u_{j+1}^{n+1} =\frac r2u_{j-1}^{n}+(1-r)u_j^n+\frac r2u_{j+1}^{n}

For linear constant-coefficient diffusion it is stable at every positive time step and second order in both space and time. However, for large rr, the amplification of high-frequency modes approaches −1-1. Alternating oscillations and unphysical negative values can appear. Stability is neither accuracy nor positivity. Sharp initial data may benefit from smaller steps or suitable backward-Euler startup steps; observables still need verification.

import computational_physics_lab as lab
for n in (20, 40, 80):
    x, u, error = lab.heat(n=n, dt=1e-5)
    print(n, error)

Here D=L=1D=L=1, the endpoints are zero, and the initial profile is sin⁡πx\sin\pi x. The exact solution is u=e−π2tsin⁡πxu=e^{-\pi^2t}\sin\pi x. At t=0.1t=0.1, maximum errors for 20 and 40 intervals are approximately 7.565×10−47.565\times10^{-4} and 1.891×10−41.891\times10^{-4}, a factor of four apart. The laboratory uses O(N)O(N) tridiagonal elimination at each step. Its unpivoted implementation is appropriate for these well-behaved matrices, not every tridiagonal system.

For D=D(x)D=D(x), discretize interface fluxes in ut=∂x(D∂xu)u_t=\partial_x(D\partial_xu) instead of replacing it by D(x)uxxD(x)u_{xx}. Flux-based updates cancel internal exchanges pairwise and naturally conserve total content at insulated boundaries. Fixed-temperature boundaries exchange heat, so total content need not be conserved there.

8.4 Poisson, relaxation, and multigrid

For ∇2ϕ=−ρ/ϵ0\nabla^2\phi=-\rho/\epsilon_0, the two-dimensional equal-spacing update target is

ϕijtarget=14(ϕi+1,j+ϕi−1,j+ϕi,j+1+ϕi,j−1+h2ρijϵ0)\phi_{ij}^{\rm target}=\frac14\left(\phi_{i+1,j}+\phi_{i-1,j}+\phi_{i,j+1}+\phi_{i,j-1}+\frac{h^2\rho_{ij}}{\epsilon_0}\right)

Jacobi uses all neighbors from the previous iteration. Gauss–Seidel immediately uses values already updated during the current sweep. SOR follows this pointwise order and sets ϕ←(1−ω)ϕ+ωϕtarget\phi\leftarrow(1-\omega)\phi+\omega\phi^{\rm target}. For symmetric positive-definite systems, 0<ω<20<\omega<2 guarantees SOR convergence; this is not a universal statement for arbitrary matrices. Weighting an entire old array at once gives weighted Jacobi, not SOR.

Local relaxation readily removes short-wavelength error but eliminates long-wavelength error slowly. Multigrid restricts the residual to a coarser grid, where the long-wavelength error becomes easier to resolve, solves for a correction, and interpolates that correction back. Numerical Recipes §20.6 is an especially useful extension of elementary relaxation. Stop using a scaled residual criterion, and keep algebraic error below spatial discretization error.

8.5 Waves and the CFL condition

For utt=c2uxxu_{tt}=c^2u_{xx}, centered differences give

ujn+1=2ujn−ujn−1+λ2(uj+1n−2ujn+uj−1n),λ=cΔtΔxu_j^{n+1}=2u_j^n-u_j^{n-1}+\lambda^2(u_{j+1}^n-2u_j^n+u_{j-1}^n),\qquad \lambda=\frac{c\Delta t}{\Delta x}

One-dimensional stability requires λ≤1\lambda\le1; in multiple dimensions require ∑α(cΔt/Δxα)2≤1\sum_\alpha(c\Delta t/\Delta x_\alpha)^2\le1. Initialize the first step correctly. Given initial displacement u0u^0 and velocity v0v^0,

uj1=uj0+Δt vj0+λ22(uj+10−2uj0+uj−10)u_j^1=u_j^0+\Delta t\,v_j^0+\frac{\lambda^2}{2}(u_{j+1}^0-2u_j^0+u_{j-1}^0)

Omitting the velocity or half-acceleration term solves a different initial value problem. Test propagation speed, boundary reflections, and numerical dispersion. A stable wave can still travel at the wrong speed.

9. Matrices: finite-dimensional versions of continuous operators

9.1 Solve the system instead of forming its inverse

The matrix in Ax=bAx=b couples unknown quantities. Use np.linalg.solve(A, b) rather than normally calculating inv(A) @ b. Pivoted LU handles general square systems, Cholesky exploits positive-definite symmetry, and QR or SVD is useful for least squares. Small singular values reveal nearly unidentifiable directions.

PDE matrices are often sparse: each row connects only a few nearby unknowns. Dense storage wastes memory. Large symmetric positive-definite problems can use preconditioned conjugate gradients; nonsymmetric problems require an appropriate alternative Krylov method. A preconditioner improves the computational scaling of directions and speeds iteration, but does not replace residual and error checks.

9.2 Eigenvalues, orthogonality, and quantum normalization

The eigenproblem Hv=EvHv=Ev finds vectors whose direction is preserved by the operator. A Hermitian matrix, H=H†H=H^\dagger, has real eigenvalues and orthogonal eigenvectors for distinct eigenvalues. Use np.linalg.eigh rather than root finding on det⁡(H−EI)=0\det(H-EI)=0. Determinants can overflow, suffer cancellation, and make nearby roots difficult to isolate.

With ℏ=m=ω=1\hbar=m=\omega=1, the oscillator Hamiltonian is H=−12d2/dx2+x2/2H=-\frac12d^2/dx^2+x^2/2. On interior uniform-grid points,

Hjj=1h2+xj22,Hj,j±1=−12h2H_{jj}=\frac1{h^2}+\frac{x_j^2}{2},\qquad H_{j,j\pm1}=-\frac1{2h^2}

The wavefunction vanishes at the endpoints, which are excluded from the unknown vector. eigh returns vectors with ∑j∣vj∣2=1\sum_j|v_j|^2=1. Continuous normalization requires ∑jh∣ψj∣2≈1\sum_jh|\psi_j|^2\approx1, so use ψj=vj/h\psi_j=v_j/\sqrt h.

import numpy as np
import computational_physics_lab as lab
x, energies, psi = lab.harmonic_states(n=240, length=8)
dx = x[1]-x[0]
print(energies)
print(dx * (psi.T.conj() @ psi))

The first four energies are approximately 0.499862, 1.499311, 2.498208, and 3.496553, approaching n+1/2n+1/2 under refinement. Also inspect ∥Hψ−Eψ∥\|H\psi-E\psi\|, orthogonality, and wavefunction tails. Eigenvectors within a degenerate subspace can rotate; any individual eigenvector has arbitrary sign or complex phase. Elementwise comparison of two solvers’ vectors is therefore generally inappropriate.

Experiment: double grid resolution at fixed box length, then enlarge the box at fixed spacing. Explain why higher excited states are affected earlier by boundaries and limited resolution. Numerical Recipes Chapters 2 and 11 offer different tools for linear solves and eigenproblems; do not confuse the two tasks.

10. Periodic potentials, Bloch’s theorem, and plane-wave bands

10.1 How periodicity reduces the problem

In a crystal, V(r+R)=V(r)V(\mathbf r+\mathbf R)=V(\mathbf r). The Hamiltonian commutes with lattice translations, giving eigenstates of the form

ψnk(r)=eik⋅runk(r),unk(r+R)=unk(r)\psi_{n\mathbf k}(\mathbf r)=e^{i\mathbf k\cdot\mathbf r}u_{n\mathbf k}(\mathbf r),\qquad u_{n\mathbf k}(\mathbf r+\mathbf R)=u_{n\mathbf k}(\mathbf r)

k\mathbf k labels crystal momentum. Labels differing by a reciprocal lattice vector can be folded into the first Brillouin zone. Bloch’s theorem follows from translation symmetry of the Hamiltonian; a periodic-looking density plot is not a substitute for that condition.

Expand the periodic part as u=∑GcGeiG⋅ru=\sum_{\mathbf G}c_{\mathbf G}e^{i\mathbf G\cdot\mathbf r}. Projection gives

HGG′(k)=ℏ2∣k+G∣22mδGG′+VG−G′,VG=1Ω∫cellV(r)e−iG⋅rdrH_{\mathbf G\mathbf G'}(\mathbf k)=\frac{\hbar^2|\mathbf k+\mathbf G|^2}{2m}\delta_{\mathbf G\mathbf G'}+V_{\mathbf G-\mathbf G'},\qquad V_{\mathbf G}=\frac1\Omega\int_{\rm cell}V(\mathbf r)e^{-i\mathbf G\cdot\mathbf r}d\mathbf r

The differential equation has become a matrix eigenproblem. For a real potential, V−G=VG∗V_{-\mathbf G}=V_{\mathbf G}^*, so the matrix must be Hermitian. This check detects Fourier-sign, index, and normalization mistakes.

10.2 A calculable band gap

Take period a=2πa=2\pi, ℏ=m=1\hbar=m=1, and V(x)=V0cos⁡xV(x)=V_0\cos x. Only V±1=V0/2V_{\pm1}=V_0/2 are nonzero, coupling adjacent reciprocal vectors. Without a potential, the energies are folded parabolas EG(k)=(k+G)2/2E_G(k)=(k+G)^2/2. At the zone boundary k=1/2k=1/2, two free states are degenerate; a weak-potential two-state approximation predicts a gap ∣V0∣|V_0|.

import numpy as np
import computational_physics_lab as lab
for k in np.linspace(-0.5, 0.5, 9):
    print(k, lab.cosine_bands(k, cutoff=5, amplitude=0.2)[:3])

For V0=0.2V_0=0.2, the calculated first gap is approximately 0.19802, close to the weak-potential estimate. Setting the amplitude to zero must recover the free-particle result exactly within the chosen basis. The periodic square well from the lectures follows the same procedure with different Fourier coefficients.

10.3 Cutoff energy, k points, and FFTs

A finite basis usually retains plane waves with kinetic energy below EcutE_{\rm cut}. The small laboratory example instead fixes an integer reciprocal-vector range to make the matrix transparent. Converge the basis at each kk, and separately converge the k-point sampling used for Brillouin-zone integrals or band extrema. A high-symmetry path alone need not locate the true gap.

A direct discrete Fourier transform commonly costs O(N2)O(N^2), while FFTs reduce the cost on standard grids to O(Nlog⁡N)O(N\log N). Kinetic energy is simple in reciprocal space and a local potential is simple in real space; FFTs connect the representations. The real-space grid must also resolve products of the potential and wavefunction to avoid aliasing.

Numerical Recipes §20.7 explains the potentially rapid convergence of spectral expansions for smooth functions. A square-well discontinuity makes Fourier coefficients decay more slowly, so the same convergence speed cannot be expected. Supercells describe defects, slabs, and isolated clusters, but their periodic images interact; converge the cell dimensions or vacuum thickness. A plane-wave basis is a representation and does not by itself supply electron correlation or a self-consistent field.

11. Transfer matrices: interface matching and probability current

11.1 Define what the matrix transfers

In a constant-potential region, ψ=Aeikx+Be−ikx\psi=Ae^{ikx}+Be^{-ikx} with k=2m(E−V)/ℏk=\sqrt{2m(E-V)}/\hbar. Interfaces normally match the wavefunction and its derivative; the corresponding effective-mass model instead matches ψ\psi and (1/m)ψ′(1/m)\psi'. Textbooks use different propagation directions and amplitude origins, so specify the convention before multiplying matrices.

For constant mass and width dd, the state (ψ,ψ′)T(\psi,\psi')^T propagates from left to right as

(ψ(x+d)ψ′(x+d))=(cos⁡kdsin⁡(kd)/k−ksin⁡(kd)cos⁡kd)(ψ(x)ψ′(x))\begin{pmatrix}\psi(x+d)\\\psi'(x+d)\end{pmatrix} =\begin{pmatrix}\cos kd&\sin(kd)/k\\-k\sin(kd)&\cos kd\end{pmatrix} \begin{pmatrix}\psi(x)\\\psi'(x)\end{pmatrix}

For several regions, matrices act in physical propagation order, with the first region’s matrix on the right. At k→0k\to0, use the limit sin⁡(kd)/k→d\sin(kd)/k\to d to avoid division by zero.

11.2 Transmission is a current ratio

Let the incoming amplitude on the left be 1, the reflected amplitude rr, and the sole outgoing amplitude on the right tt. Plane-wave current is j=(ℏk/m)∣A∣2j=(\hbar k/m)|A|^2. When both leads support propagating channels,

R=∣r∣2,T=kR/mRkL/mL∣t∣2R=|r|^2,\qquad T=\frac{k_R/m_R}{k_L/m_L}|t|^2

Only equal lead velocities give T=∣t∣2T=|t|^2. For a real, nonabsorbing single-channel potential, R+T=1R+T=1 is a central check. Omitting the velocity factor for unequal asymptotic potentials can create an artificial violation of conservation; asymmetric scattering potentials especially require care.

Inside a barrier with E<VE<V, use k=iκk=i\kappa. Exponential decay inside the barrier does not imply exactly zero transmission. For a rectangular barrier between equal-potential leads and 0<E<V00<E<V_0,

T=[1+V02sinh⁡2(κd)4E(V0−E)]−1,κ=2m(V0−E)ℏT=\left[1+\frac{V_0^2\sinh^2(\kappa d)}{4E(V_0-E)}\right]^{-1},\quad \kappa=\frac{\sqrt{2m(V_0-E)}}\hbar

lab.barrier(E=0.5, height=1, width=1) uses m=ℏ=1m=\hbar=1 and gives T≈0.41997434T\approx0.41997434, R≈0.58002566R\approx0.58002566, matching the analytical expression. Vary thickness to observe exponential tunneling suppression; above the barrier, interference produces oscillations.

11.3 Why thick barriers are numerically dangerous

A transfer matrix simultaneously carries eκde^{\kappa d} and e−κde^{-\kappa d}. Thick barriers, many layers, or many closed channels produce severe scale separation, ill-conditioning, and overflow. Higher precision postpones the difficulty. Research implementations often need scattering-matrix composition, stabilized factorizations, or logarithmic derivatives.

Numerical Recipes does not provide a complete scattering course here, but §1.1 on growing error modes, §2.6 on conditioning, and Chapter 18 on boundary matching explain the numerical issues. Experiment: recover R→0R\to0 for zero potential and T→1T\to1 for vanishing thickness, then compare matrix and analytical results across energies. The laboratory implementation is intended for moderate thickness and explicitly excludes the special limit E=V0E=V_0.

12. Molecular dynamics: constructing a physical particle model

12.1 What MD solves

Classical molecular dynamics (MD) advances

mir¨i=Fi=−∇iU(r1,…,rN)m_i\ddot{\mathbf r}_i=\mathbf F_i=-\nabla_iU(\mathbf r_1,\ldots,\mathbf r_N)

Electronic effects are usually incorporated into a potential-energy model; first-principles MD instead computes electronic structure during nuclear motion. The Born–Oppenheimer approximation exploits the mass and time-scale separation between electrons and nuclei, allowing electrons to approximately follow a given nuclear configuration. Classical nuclei can fail for low temperatures, light elements, zero-point motion, or tunneling. Numerically precise trajectories do not supply missing physics.

A first MD project should have an interpretable target, such as measuring radial structure at a specified temperature and density, or comparing diffusion at two temperatures. Start with the observable rather than the largest possible atom count.

12.2 Lennard–Jones energy and forces

The Lennard–Jones (LJ) pair potential is

U(r)=4ε[(σ/r)12−(σ/r)6]U(r)=4\varepsilon\left[(\sigma/r)^{12}-(\sigma/r)^6\right]

Short-range repulsion suppresses overlap, while the attractive term models dispersion. U(σ)=0U(\sigma)=0, and the minimum at r=21/6σr=2^{1/6}\sigma has depth −ε-\varepsilon. With rij=ri−rj\mathbf r_{ij}=\mathbf r_i-\mathbf r_j,

Fij=24ε[2(σ/r)12−(σ/r)6]rijr2\mathbf F_{ij}=24\varepsilon\left[2(\sigma/r)^{12}-(\sigma/r)^6\right]\frac{\mathbf r_{ij}}{r^2}

Evaluate each unordered pair once and add equal and opposite forces, helping preserve total momentum. Check force directions for two atoms, zero force at the minimum, and agreement between the analytic force and a numerical energy gradient.

A cutoff rcr_c is commonly imposed. Subtracting U(rc)U(r_c) makes energy continuous but does not make the force continuous. A force-shifted model uses, for r<rcr<r_c,

Ufs(r)=U(r)−U(rc)−(r−rc)U′(rc),Ffs(r)=F(r)−F(rc)U_{\rm fs}(r)=U(r)-U(r_c)-(r-r_c)U'(r_c),\qquad F_{\rm fs}(r)=F(r)-F(r_c)

and sets both quantities to zero beyond the cutoff. The laboratory uses this consistent pair. It changes the original LJ model: a smooth cutoff does not eliminate cutoff error. Tail corrections usually assume a homogeneous far field with g(r)≈1g(r)\approx1 and require care for interfaces or strongly nonuniform systems.

12.3 Choose the force model before extending the trajectory

ModelMain structureUses and limits
LJ, Morse, BuckinghamPair-distance functionsNoble gases and effective interactions; limited descriptions of bond direction and changing environment
CoulombLong-range charge interactionIonic and polar systems; a simple hard cutoff is usually inadequate, motivating Ewald or particle-mesh treatments
EAMEmbedding energy plus pair termsMetals; depends on a local electron-density surrogate and needs transferability checks
Stillinger–WeberPair terms and explicit three-body anglesCovalent networks and specific material models
Tersoff/BrennerEnvironment-dependent bond orderDirectional bonding for supported elements and environments
MEAMEmbedding framework with angular informationExtended metallic and some more complex bonding environments
Molecular force fieldsBonds, angles, torsions, and nonbonded termsOrganic and biological molecules; topology, constraints, and parameter scope matter

For example, EAM has U=∑iF(ρi)+12∑i≠jϕ(rij)U=\sum_iF(\rho_i)+\frac12\sum_{i\ne j}\phi(r_{ij}) with ρi=∑j≠if(rij)\rho_i=\sum_{j\ne i}f(r_{ij}). Environmental dependence makes its force more than a fixed pair derivative. Reproducing a fitted lattice constant does not guarantee accurate defects, surfaces, high pressure, or melting. Validate properties relevant to the actual research question.

12.4 Units, initial conditions, and periodic boundaries

LJ reduced units are

r∗=r/σ,E∗=E/ε,t∗=t/(σm/ε),T∗=kBT/ε,p∗=pσ3/εr^*=r/\sigma,\quad E^*=E/\varepsilon,\quad t^*=t/\left(\sigma\sqrt{m/\varepsilon}\right),\quad T^*=k_BT/\varepsilon,\quad p^*=p\sigma^3/\varepsilon

Initialize on a lattice or with a nonoverlapping random arrangement. Maxwell velocities have variance kBT/mk_BT/m per Cartesian component. After removing center-of-mass velocity, account for the remaining degrees of freedom when assigning temperature. Nearly overlapping atoms produce enormous repulsion; a thermostat should not conceal a bad initial structure. Minimize energy when appropriate and equilibrate gradually.

Periodic boundaries wrap a particle leaving one face back through the opposite face. In an orthorhombic box with lengths LαL_\alpha, minimum-image displacement is

Δrα←Δrα−Lαround⁡(Δrα/Lα)\Delta r_\alpha\leftarrow\Delta r_\alpha-L_\alpha\operatorname{round}(\Delta r_\alpha/L_\alpha)

The simple minimum-image short-range algorithm requires rc<12min⁡Lαr_c<\frac12\min L_\alpha. Skewed cells need appropriate lattice geometry, not direct reuse of this componentwise orthogonal formula. Wrapped coordinates help with local interactions; unwrapped coordinates or image counters are needed for diffusion.

12.5 Neighbor lists and an integration cycle

A neighbor list stores candidate pairs within rc+rskinr_c+r_{\rm skin}; force evaluation still applies r<rcr<r_c. Rebuild when the largest displacement since construction exceeds rskin/2r_{\rm skin}/2. A sharper criterion uses the sum of the two largest displacements. A fixed update interval can miss fast-moving neighbors.

Spatial bins restrict searches to nearby bins. At fixed density and interaction range, the work can approach O(N)O(N). For transparency, the laboratory’s lj_force uses an O(N2)O(N^2) pair calculation suitable for small verification systems.

One MD cycle is: half-step velocity → full-step position → boundaries and neighbor-list maintenance → new forces → half-step velocity → sampling. lab.md() demonstrates a short 64-particle NVE run. Over its default 0.8 reduced time units, the maximum energy change per particle is approximately 7.47×10−57.47\times10^{-5}. This checks the force/integrator combination; it is not an equilibrated liquid diffusion measurement.

Experiment: integrate the same physical duration with hh and h/2h/2 and compare energy errors. Then vary the cutoff to distinguish time discretization from a change in the truncated potential. Compare a neighbor-list implementation against all-pairs forces step by step on a small system.

13. Ensembles, temperature, pressure, and heat baths

13.1 The ensemble defines the distribution to sample

EnsembleFixed quantitiesTypical use
NVEParticle number, volume, energyIsolated systems, integrator checks, suitable dynamical measurements
NVTParticle number, volume, temperatureEquilibrium at fixed temperature
NPTParticle number, pressure, temperatureDensity, thermal expansion, structures at fixed pressure
μ\muVTChemical potential, volume, temperatureParticle reservoirs, adsorption, open systems

The canonical density is π(r,p)∝e−βH\pi(\mathbf r,\mathbf p)\propto e^{-\beta H}, with β=1/(kBT)\beta=1/(k_BT). The partition function normalizes it. MC acceptance uses probability ratios, often avoiding direct evaluation of this high-dimensional integral. Replacing ensemble averages by time averages requires suitable ergodicity and adequate sampling. A long trajectory trapped in a metastable region may still be unrepresentative.

13.2 Instantaneous temperature and virial pressure

With ff effective momentum degrees of freedom,

Tinst=2KfkB,K=12∑imivi2T_{\rm inst}=\frac{2K}{fk_B},\qquad K=\frac12\sum_im_iv_i^2

In three dimensions with center-of-mass motion removed and no other constraints, typically f=3N−3f=3N-3. Rigid bonds and other constraints remove further degrees of freedom. Instantaneous temperature is supposed to fluctuate. Exact agreement with the target at every step is not evidence of correct canonical sampling.

For a simple pair-interaction system in dd dimensions,

p=2K+∑i<jrij⋅FijdVp=\frac{2K+\sum_{i<j}\mathbf r_{ij}\cdot\mathbf F_{ij}}{dV}

The first contribution is kinetic, the second the interaction virial. Use the same periodic displacements and cutoff conventions as in force calculations. Constraint forces, long-range corrections, and many-body potentials require their corresponding pressure contributions.

13.3 What a thermostat changes

Simple velocity rescaling can rapidly adjust temperature but suppresses kinetic fluctuations. Berendsen weak coupling provides feedback toward the target and can be useful in preparation, but does not reproduce canonical fluctuations. Andersen random collisions can sample the canonical distribution while changing momentum correlations and transport.

Langevin dynamics is

mv˙=−∂xU−mγv+2mγkBT η(t),⟨η(t)η(t′)⟩=δ(t−t′)m\dot v=-\partial_xU-m\gamma v+\sqrt{2m\gamma k_BT}\,\eta(t),\qquad \langle\eta(t)\eta(t')\rangle=\delta(t-t')

The relation between noise strength and friction establishes thermal equilibrium under suitable conditions. Discrete random increments scale as Δt\sqrt{\Delta t} rather than Δt\Delta t; use an appropriate stochastic integrator. Strong damping alters diffusion and vibrational spectra.

Nosé–Hoover introduces deterministic feedback through additional bath variables, but small or nearly integrable systems need not be ergodic. Thermostat chains can improve sampling without providing a universal guarantee. An NPT barostat also changes volume or cell shape and requires the correct ensemble measure and appropriate coupling time scales.

Experiment: inspect the distribution as well as the mean of kinetic energy under a thermostat, and compare velocities with the Maxwell distribution. For diffusion or viscosity, report the thermostat and coupling strength and test their effect on the measured coefficient.

14. Analyzing MD: structure, diffusion, and uncertainty

14.1 From a trajectory to structure

The radial distribution function g(r)g(r) compares local number density around a particle with a homogeneous reference. For an isotropic three-dimensional one-component system, the shell volume is

ΔVk=4π3(rk+13−rk3)\Delta V_k=\frac{4\pi}{3}(r_{k+1}^3-r_k^3)

If each frame counts unordered pairs and their frame-averaged count is ⟨Ck⟩\langle C_k\rangle, a finite-NN ideal-gas normalization is

gk=2V⟨Ck⟩N(N−1)ΔVkg_k=\frac{2V\langle C_k\rangle}{N(N-1)\Delta V_k}

Its expectation is one for a uniform ideal gas. In a simple periodic box, normally restrict r<Lmin⁡/2r<L_{\min}/2. Do not include the factor of two again if counting ordered pairs. In the thermodynamic limit, coordination is often written nc≈4πρ∫0rmin⁡r2g(r)drn_c\approx4\pi\rho\int_0^{r_{\min}}r^2g(r)dr. With the finite-system normalization above, the corresponding neighbor density is (N−1)/V(N-1)/V. Here rmin⁡r_{\min} denotes the first minimum after the first peak, not the smallest pair distance.

The structure factor

S(k)=1N⟨∣∑jeik⋅rj∣2⟩S(\mathbf k)=\frac1N\left\langle\left|\sum_je^{i\mathbf k\cdot\mathbf r_j}\right|^2\right\rangle

connects atomic arrangements to scattering. Account for the trivial density contribution at k=0\mathbf k=0 and for the wavevectors allowed by a periodic box. Crystal peaks, broad liquid peaks, and local bond-angle distributions describe different structural features.

14.2 MSD and Green–Kubo

Mean-square displacement is

MSD⁡(t)=1N∑i⟨∣ri(t0+t)−ri(t0)∣2⟩t0\operatorname{MSD}(t)=\frac1N\sum_i\left\langle|\mathbf r_i(t_0+t)-\mathbf r_i(t_0)|^2\right\rangle_{t_0}

Use continuous unwrapped coordinates across periodic boundaries. For equilibrium isotropic diffusion at long times, MSD⁡(t)∼2dDt\operatorname{MSD}(t)\sim2dDt, so divide its slope by 2d2d. Short-time inertial motion is ballistic and scales as t2t^2; confined particles may produce a plateau. Do not force a linear fit over an arbitrary interval. Remove unintended center-of-mass drift, while modeling genuine flow as a separate physical signal.

Velocity autocorrelation provides another route:

D=1d∫0∞⟨v(0)⋅v(t)⟩dtD=\frac1d\int_0^\infty\langle\mathbf v(0)\cdot\mathbf v(t)\rangle dt

This follows by expressing displacement as an integral of velocity and connects Einstein and Green–Kubo diffusion estimates. Correlation tails become noisy, requiring convergence checks on the integration limit. Finite boxes and hydrodynamic effects can also influence the coefficient.

14.3 FFTs and sampling intervals

A discrete Fourier transform resolves a time series into frequencies. Sampling interval Δts\Delta t_s sets Nyquist frequency fN=1/(2Δts)f_N=1/(2\Delta t_s); total duration TT sets resolution of order 1/T1/T. Recording longer cannot recover high-frequency information already lost to aliasing.

When computing a finite sequence’s linear autocorrelation by FFT, pad with zeros to avoid circular wraparound. Subtract the mean, normalize by the number of available pairs at each lag, and state the convention. The laboratory’s autocorrelation pads to 2N2N and divides by N−kN-k. Large lags have few pairs and noisy estimates, so blindly integrating every lag is unreliable.

14.4 Equilibration, correlation, and melting

Check equilibration using energy, temperature, density, and structure before collecting production data. Discarding the first 10% is not a universal equilibration rule. Multiple time origins reduce variance, but overlapping windows are not independent experiments.

Blocking divides a production sequence into contiguous blocks of length BB, computes each block mean Aˉb\bar A_b, and estimates SE as the standard deviation of block means divided by the square root of the number of blocks. Increase BB and look for a reasonably stable error estimate while retaining enough blocks. No plateau can indicate an inadequate trajectory or lack of equilibrium.

An abrupt energy or volume change during heating may indicate melting, but a perfect crystal can superheat, and cooling can produce supercooling. Reliable melting studies consider solid–liquid coexistence, size effects, waiting times, and thermodynamic path. Experiment: compare MSD and velocity-correlation diffusion estimates from the same trajectory, then vary fitting windows, duration, and box size separately. Connect every conclusion to its relevant uncertainty.

15. Random walks, Markov chains, and Metropolis sampling

15.1 Random walks connect probability to diffusion

A one-dimensional walker independently moves left or right by aa with equal probability at each step. Then ⟨xn⟩=0\langle x_n\rangle=0 and ⟨xn2⟩=na2\langle x_n^2\rangle=na^2. If each step takes Δt\Delta t, comparison with ⟨x2⟩=2Dt\langle x^2\rangle=2Dt gives D=a2/(2Δt)D=a^2/(2\Delta t). The probability recurrence

Pjn+1=12(Pj−1n+Pj+1n)P_j^{n+1}=\frac12(P_{j-1}^n+P_{j+1}^n)

becomes the diffusion equation in an appropriate continuum limit. Discrete random paths and a continuous PDE describe the same kind of macroscopic transport.

A self-avoiding walk cannot revisit occupied sites and models polymer excluded volume. Naive sequential growth can reach a dead end, requiring a termination or restart rule; it also need not sample fixed-length self-avoiding paths uniformly. The three-dimensional Flory estimate R∼N3/5R\sim N^{3/5} is an approximate scaling law, not an exact exponent. In diffusion-limited aggregation (DLA), walkers stick on reaching a cluster and generate branched structures. This is irreversible growth, not equilibrium MCMC.

15.2 Stationarity and detailed balance

The Markov property states that, given the present state, the next-state distribution does not depend on earlier history. Use the row-stochastic convention Pij=Pr⁡(Xn+1=j∣Xn=i)P_{ij}=\Pr(X_{n+1}=j\mid X_n=i), with each row summing to one. Distributions evolve as pn+1=pnPp_{n+1}=p_nP; a stationary distribution satisfies π=πP\pi=\pi P.

Detailed balance,

πiPij=πjPji\pi_iP_{ij}=\pi_jP_{ji}

equates equilibrium flow between each pair of states. It is sufficient for stationarity but not necessary. A finite chain also needs suitable irreducibility and aperiodicity for convergence from arbitrary starting states to a unique stationary distribution. A nearest-neighbor walk on an even ring has period two; allowing a chance of staying removes that periodicity.

15.3 Deriving Metropolis–Hastings

From state xx, propose yy using q(y∣x)q(y|x) and accept with

α(x,y)=min⁡(1,π(y)q(x∣y)π(x)q(y∣x))\alpha(x,y)=\min\left(1,\frac{\pi(y)q(x|y)}{\pi(x)q(y|x)}\right)

The product π(x)q(y∣x)α(x,y)\pi(x)q(y|x)\alpha(x,y) equals the smaller of the forward and reverse weights. It is unchanged under exchanging xx and yy, establishing detailed balance. Unknown normalization cancels in the ratio.

For canonical configurations, π∝e−βU\pi\propto e^{-\beta U}, a symmetric proposal gives min⁡(1,e−βΔU)\min(1,e^{-\beta\Delta U}). A rejection keeps the current state, and that repeated state must count as a sample. Keeping only accepted states changes the distribution. A log-domain comparison avoids exponential overflow:

log⁡u<min⁡(0,log⁡π(y)−log⁡π(x)+log⁡q(x∣y)−log⁡q(y∣x))\log u<\min(0,\log\pi(y)-\log\pi(x)+\log q(x|y)-\log q(y|x))

Tiny moves give strong correlation; enormous moves are frequently rejected. An acceptance rate near one half is a heuristic for some problems, not a universal optimum. Compare effective samples per unit cost. Tune proposal scales during warmup and then hold them fixed for production unless using a justified adaptive scheme.

15.4 Correlated samples are not independent samples

With normalized autocorrelation ρ(k)\rho(k), a common convention is

τint=12+∑k=1∞ρ(k),Neff≈N2τint,SE(Aˉ)≈2τintVar⁡(A)N\tau_{\rm int}=\frac12+\sum_{k=1}^\infty\rho(k),\qquad N_{\rm eff}\approx\frac{N}{2\tau_{\rm int}},\qquad \mathrm{SE}(\bar A)\approx\sqrt{\frac{2\tau_{\rm int}\operatorname{Var}(A)}N}

Time is measured in sampling intervals. Different observables have different correlation times. Truncate the correlation sum sensibly or use robust windows; a long noisy tail destabilizes the estimate. Thinning usually reduces storage rather than creating information.

Chains from dispersed starting states, trace plots, block uncertainties, and consistent parameter distributions collectively help assess mixing. No single diagnostic proves that every important region has been visited. Numerical Recipes §15.8 applies the same method to Bayesian posteriors, π(θ)∝P(D∣θ)P(θ)\pi(\theta)\propto P(D|\theta)P(\theta). Low-energy regions in statistical physics correspond to high-posterior regions in inference. Barriers and narrow correlated directions impede both.

16. The Ising model: a complete equilibrium Monte Carlo project

16.1 Local flips and energy differences

Each site of a square lattice has si=±1s_i=\pm1, with energy

E=−J∑⟨ij⟩sisj−h∑isiE=-J\sum_{\langle ij\rangle}s_is_j-h\sum_i s_i

Count each nearest-neighbor bond once. Flipping a spin changes only its four adjacent bonds and field term, giving

ΔE=2si(J∑j∈nn(i)sj+h)\Delta E=2s_i\left(J\sum_{j\in\mathrm{nn}(i)}s_j+h\right)

At zero field, ΔE∈{−8J,−4J,0,4J,8J}\Delta E\in\{-8J,-4J,0,4J,8J\}, so acceptance factors can be precomputed. Choose a random site, calculate its local energy change, and accept using Metropolis. N=L2N=L^2 attempts define a sweep; random selection permits repeated visits to a site within one sweep.

16.2 Observables and fluctuation formulas

Let total magnetization be M=∑isiM=\sum_i s_i and magnetization per spin m=M/Nm=M/N. Heat capacity and susceptibility per spin are

cV=⟨E2⟩−⟨E⟩2NkBT2,χ=βN(⟨M2⟩−⟨M⟩2)c_V=\frac{\langle E^2\rangle-\langle E\rangle^2}{Nk_BT^2},\qquad \chi=\frac{\beta}{N}(\langle M^2\rangle-\langle M\rangle^2)

They follow from partition-function derivatives with respect to temperature and field, connecting equilibrium fluctuations to response. At zero field, a sufficiently sampled finite system may have ⟨M⟩=0\langle M\rangle=0, so ⟨∣m∣⟩\langle|m|\rangle often displays ordering more clearly. Replacing ⟨M⟩2\langle M\rangle^2 by ⟨∣M∣⟩2\langle|M|\rangle^2 inside the susceptibility formula silently defines a different observable and must be distinguished.

For the infinite, zero-field, nearest-neighbor ferromagnetic square-lattice model,

kBTcJ=2ln⁡(1+2)≈2.269185\frac{k_BT_c}{J}=\frac2{\ln(1+\sqrt2)}\approx2.269185

Finite systems show broadened, shifted peaks rather than a guaranteed sharp singularity at this value. Local flips become strongly correlated near criticality, motivating longer runs or suitable cluster algorithms. The Binder ratio U4=1−⟨m4⟩/(3⟨m2⟩2)U_4=1-\langle m^4\rangle/(3\langle m^2\rangle^2) compared across sizes is a further route to critical behavior, with corrections and uncertainties still needing analysis.

16.3 Run and verify

import computational_physics_lab as lab
samples = lab.ising(L=12, temperature=2.5, burn=1000, sweeps=4000, seed=17)
energy, magnetization = samples.T
for B in (20, 50, 100, 200):
    print(B, lab.block_summary(energy, B))
print("mean absolute magnetization:", abs(magnetization).mean())

These lengths are starting points, not guarantees of equilibration or precision. Compare ordered and random initial conditions, increase warmup and production, and check statistical agreement. Nonlinear quantities such as heat capacity and susceptibility can use block jackknife or block bootstrap uncertainties; resample approximately independent blocks.

The laboratory checks all 4,608 single-spin moves from the 512 possible 3×33\times3 configurations, comparing local energy changes with full energy differences and verifying the detailed-balance acceptance ratio. This catches periodic-index and bond-counting mistakes. A further test enumerates all states to calculate Z=∑se−βEsZ=\sum_s e^{-\beta E_s} and exact averages, then compares MC. Subtract the minimum energy before exponentiating to stabilize weights.

Experiment: compute magnetization, energy, and correlation times versus temperature for L=8,12,16L=8,12,16. Report sample count, sampling interval, warmup, and error bars. Do not label a finite-size curve as the thermodynamic limit.

17. Kinetic Monte Carlo: assigning physical time to random events

17.1 Equilibrium moves do not automatically represent time

A Metropolis attempt usually has no directly assigned physical duration. Kinetic Monte Carlo (KMC) starts from meaningful transition rates and simulates a continuous-time Markov process. It suits systems with long residence in metastable states and short transitions describable by rates, such as hopping diffusion, adsorption/desorption, and reactions.

A common thermally activated rate is

ri→j=νijexp⁡[−β(Eij‡−Ei)]r_{i\to j}=\nu_{ij}\exp[-\beta(E_{ij}^{\ddagger}-E_i)]

A rate has inverse-time units. E‡−EiE^\ddagger-E_i is the escape barrier from the current state, not simply the energy difference between final and initial states. Prefactors, barriers, and the event catalog all require physical justification.

17.2 Select an event and a waiting time

At the current state, let available rates be r1,…,rMr_1,\ldots,r_M and total rate R=∑jrjR=\sum_jr_j. Survival over a short interval is approximately 1−Rdt1-Rdt, giving S′(t)=−RS(t)S'(t)=-RS(t) and S(t)=e−RtS(t)=e^{-Rt}. Therefore,

Pr⁡(j is next)=rjR,Δt=−ln⁡UR\Pr(j\text{ is next})=\frac{r_j}{R},\qquad \Delta t=-\frac{\ln U}{R}

Use the current state’s rates to draw the event and waiting time. Attribute that residence to the current state, execute the event, and update affected rates. If R=0R=0, the state is absorbing; do not divide by zero. Waiting times are exponentially distributed. Counts of independent events at a constant rate follow a Poisson distribution.

The Gillespie reaction simulation in Numerical Recipes §17.7 has the same mathematical structure. Its dependency graph identifies which local rates need updating after an event. Cumulative sums with linear search are simple; trees can accelerate a large event catalog. Explicitly time-dependent rates require integrated hazards or another appropriate method rather than direct use of a constant-RR exponential waiting time.

17.3 Weight averages by residence time

If state xnx_n persists for Δtn\Delta t_n,

A‾=∑nA(xn)Δtn∑nΔtn\overline A=\frac{\sum_nA(x_n)\Delta t_n}{\sum_n\Delta t_n}

Consider A⇌BA\rightleftharpoons B with rAB=2r_{AB}=2, rBA=1r_{BA}=1. Events alternate, so event counts assign half the observations to each state. But the mean residence is 1/2 time unit in AA and one unit in BB, giving stationary occupations (1/3,2/3)(1/3,2/3). lab.kmc_two_state() gives approximately (0.33416,0.66584)(0.33416,0.66584). This distinguishes averaging events from measuring time averages.

Experiment: multiply both rates by ten. Stationary occupation should remain unchanged while physical times shrink tenfold. Omit a transition channel and observe the changed prediction. KMC can sample its specified Markov model exactly, while an incomplete catalog, incorrect barriers, or neglected memory still create model error.

18. From exercises to research: fitting, optimization, and reproducible evidence

18.1 Parameter estimation needs a statistical model

For yi≈f(xi;θ)y_i\approx f(x_i;\theta) with independent normal errors of known standard deviation σi\sigma_i, maximum likelihood minimizes

χ2=∑i[yi−f(xi;θ)]2σi2\chi^2=\sum_i\frac{[y_i-f(x_i;\theta)]^2}{\sigma_i^2}

Correlated errors require a residual vector rr and covariance CC: χ2=rTC−1r\chi^2=r^TC^{-1}r. Evaluate this through factorization or solves rather than explicitly forming an inverse. Overlapping MSD time points are strongly correlated, so a line fit’s default uncertainty may be too small. Estimate diffusion separately from independent trajectories or long blocks and analyze those estimates.

“Linear” least squares refers to linearity in parameters: a0+a1x+a2x2a_0+a_1x+a_2x^2 is a linear model. Solve the design-matrix problem through QR or SVD instead of unnecessarily forming normal equations that square the condition number. Numerical Recipes §§15.1 and 15.4 connect fitting to its error assumptions, a more useful lesson than remembering a fitting function name.

Nonlinear optimization requires initial guesses, parameter scaling, constraints, and checks from multiple starting points. In energy minimization the gradient is minus the force; a local minimum need not be the global lowest-energy structure. Optimization convergence, a small equation residual, and a small statistical error answer different questions.

18.2 Preserve six types of evidence

  1. Model definition: equations, units, boundaries, potential parameters, ensemble, and observable.
  2. Benchmarks: analytical limits, exact enumeration, or an independent numerical method.
  3. Numerical convergence: separate changes to time step, mesh, box, basis, and cutoff.
  4. Statistical reliability: equilibration, correlation times, effective sample counts, independent repetitions, and error bars.
  5. Reproducibility: inputs, seeds, software versions, code version, raw data, and plotting scripts.
  6. Physical interpretation: supported conclusions, differences exceeding uncertainty, and remaining model assumptions.

A useful project layout separates src/, inputs/, data/, analysis/, and figures/. Preserve raw data. Give parameter-sweep jobs separate output files, run identifiers, and units. Profile before optimizing, then rerun the original benchmarks after changes.

18.3 A method-selection table

ProblemReasonable starting pointAdditional checks
Smooth one-dimensional integralAdaptive or Gaussian quadratureSingularities, narrow peaks, absolute tolerance
High-dimensional integralMC, importance sampling, randomized quasi-MCWeight variance and uncertainty assumptions
Nonstiff initial value problemAdaptive RKEvents, scales, observable convergence
Long conservative dynamicsSuitable symplectic integrationTime step, energy, and phase
Stiff initial value problemImplicit methodsJacobian, nonlinear solves, accuracy
Linear systemStructure-aware factorization or iterationConditioning, residuals, preconditioning
Hermitian eigenproblemeigh or a suitable sparse solverOrthogonality, residuals, basis/grid
Elliptic PDEMultigrid or preconditioned sparse methodsBoundary compatibility, discretization error
Equilibrium statisticsMD or MCMCEnsemble, ergodicity, correlation
Rare-event dynamicsKMC with physical ratesEvent completeness, residence-time weighting

Describe the result with a testable statement, such as: “For this potential, density, and temperature, the diffusion coefficient agrees within the reported uncertainty across three box sizes and two time steps.” This contains substantially more scientific information than “the simulation ran successfully.”

19. A thirty-day study and practice route

Allow roughly two to three hours daily: read concepts and derivations, write or modify a program, then record one verification result. Week one establishes foundations, week two solves fields and quantum problems, week three enters particle and statistical simulation, and week four integrates the methods into a project. When time is short, reduce system size or parameter range while retaining verification.

DayStudy and implementationEvidence to retain
1Environment, variables, arrays, loops, functionsRun the laboratory; explain files, terminal, and interpreter
2Units, nondimensionalization, memory, complexityScale the oscillator and estimate matrix storage
3Floating point, cancellation, conditioningCompare square-root expressions and identify errors
4Trapezoid, Simpson, Taylor expansionAn integration error table and second/fourth-order ratios
5Romberg, adaptivity, Gaussian rules, singularitiesCompare performance on smooth and cornered functions
6MC integration, seeds, standard errorError versus sample size across independent seeds
7Importance sampling and differentiationA derivative-error table or plot; first-week review
8Euler, Euler–Cromer, VerletEnergy and phase for the same oscillator
9RK4, adaptivity, stiffnessShort-time order and an explanation of stiff stability limits
10Satellite or driven pendulumOne verified limit and one nontrivial trajectory
11Bisection, Newton, Brent, shootingA simple boundary solution and residual
12Numerov, quantum boundaries, matchingThree well energies and mesh convergence
13Explicit/CN diffusion, tridiagonal solvesSine-mode decay errors and a deliberately violated stability limit
14Poisson, waves, boundariesResidual for a known field and a correctly initialized wave
15Linear systems and Hermitian eigenproblemsOscillator energies, orthogonality, and box-size checks
16Bloch, plane waves, Fourier analysisFree-particle limit and periodic-potential gap
17Transfer matrices, current, conditioningTransmission curve and R+TR+T check
18MD potentials, reduced units, initializationTwo-atom force and energy-gradient agreement
19Verlet, PBC, neighbor listsNVE time-step convergence and total momentum
20Ensembles, temperature, pressure, thermostatsDegree-of-freedom accounting and thermostat suitability
21RDF, MSD, correlation, blockingA structural indicator and a dynamical estimate with uncertainty
22Random walks, self avoidance, DLAVerify ⟨x2⟩∝t\langle x^2\rangle\propto t and explain sampling bias
23Markov chains, balance, MetropolisStationarity in a two-state chain or small system
24Ising and correlation timeInitial-state agreement, blocking, temperature scan
25KMC and GillespieTwo-state residence fractions and uniform rate rescaling
26Select a project and its error budgetOne-page research design and minimal benchmark
27Implement and cross-checkAnalytical limit or comparison with a second method
28Numerical and statistical convergenceAt least three key resolutions and independent repetitions
29Fit, plot, and interpretFigures with units and visible uncertainties; parameter table
30Rerun and write a reportA project reproducible from a clean directory and supported conclusions

Three possible capstone projects

Quantum route: from wells to bands. Solve isolated-well bound states using finite differences and Numerov, then obtain periodic-potential bands with plane waves. Converge mesh, box, and basis. Explain the connection between isolated levels and bands. Evidence includes analytical limits, agreement between methods, normalization, and gap convergence.

Particle route: diffusion in an LJ fluid. Verify pair forces and NVE energy before equilibrating at a chosen density and temperature. Measure g(r)g(r), MSD, and velocity autocorrelation. Compare time steps, trajectory lengths, and box sizes, separating statistical and finite-size effects. A short demonstration does not replace a production trajectory; reduce the temperature scan if necessary.

Statistical route: Ising and stochastic dynamics. Check Metropolis against exact small-system enumeration and study finite-size magnetization and correlation times. Build a two-state or lattice KMC model with specified rates and compare event averages with residence-time averages. There is no default conversion from an equilibrium MC sweep to physical time.

Laboratory benchmark results

The following values come from a run with the laboratory’s default parameters. Last digits may vary with numerical libraries; random results also depend on generator and version. Broad stochastic tolerances in the checks detect conspicuous implementation mistakes and do not replace a research statistical analysis.

CheckResult or target
Trapezoid and Simpson error ratios3.999875, 15.996427
Verlet and RK4 endpoint error ratios4.002913, 15.998809
Two-dimensional integral0.18393790, approaching 1/(2e)1/(2e)
Scalar root0.73908513325
Numerov sine-solution maximum errorApproximately 3.97×10−103.97\times10^{-10}
Heat-equation mesh error ratioApproximately 4.0006
First four oscillator energies0.499862, 1.499311, 2.498208, 3.496553
First cosine-potential band gapApproximately 0.198025; weak-potential estimate 0.2
Rectangular barrierT=0.41997434T=0.41997434, R+T=1R+T=1 to roundoff
Short MD trajectoryMaximum energy change per atom approximately 7.47×10−57.47\times10^{-5}
Ising local energy differencesAll 4,608 flips agree with full energy differences
Two-state KMC residence fractionsApproximately 0.33416, 0.66584; targets 1/3, 2/3

20. Reading map: lectures and Numerical Recipes

The course source is Li Huang’s Introduction to Computational Physics, Spring 2025: the 22 lecture files below, totaling 596 pages. The reference is William H. Press, Saul A. Teukolsky, William T. Vetterling, and Brian P. Flannery, Numerical Recipes: The Art of Scientific Computing, 3rd ed., Cambridge University Press, 2007. Page references below are printed book pages . In the supplied reference PDF, body-page indices equal printed pages plus 24. Section numbers follow the third edition; PDE relaxation is §20.5.

The lectures place methods in physical settings, especially bands, scattering, MD force models, ensembles, and Ising physics. The book adds error analysis, algorithm selection, and implementation detail. The table distinguishes direct topic matches from supporting numerical tools; the latter do not replace the physical theory.

Lecture fileTutorialThird-edition correspondence and starting pagesMain insight from comparison
Lecture0 (10 pages)Roadmap, §§1, 19Chapter 1, p.1Computation as a loop of modeling, algorithms, and verification
Lecture1-introduction (21)§§1–2§1.1 p.8; §22.2 p.1163Extend computer/programming foundations to representation error and stability
Lecture2-ErrorAnalysis (19)§§2, 5§1.1 p.8; §5.7 p.229Propagation, cancellation, growing modes, optimal differentiation steps
Lecture3-NumericalIntegration (16)§3§§4.1–4.3 pp.156, 162, 166; §4.6 p.179; §4.7 p.194From fixed rules to extrapolation, Gaussian quadrature, reliable stopping
Lecture4-MonteCarloIntegration (35)§4§7.1 p.341; §7.3 p.361; §§7.7–7.9 pp.397, 403, 410Sampling transformations, standard errors, importance/stratified/quasi-MC distinctions
Lecture5-Differentiation (15)§5§5.7 p.229; §14.9 p.766Truncation versus roundoff and local fits for noisy data
Lecture6-ODE-I (25)§6§§17.1–17.2 pp.907, 910; §17.4 p.928Local/global error, cost comparisons, adaptivity, conservative second-order systems
Lecture6-ODE-II (26)§6.5§§17.1–17.2; §17.5 p.931Satellites, damping, and chaos provide context; events and stability support their calculation
Lecture6-ODE-III (42)§7§§9.1, 9.3, 9.4 pp.445, 454, 456; §§18.1–18.3 pp.959, 962, 964Root finding on boundary residuals and matching to control growing solutions
Lecture7-PDE (53)§8§20.1 p.1031; §20.2 p.1043; §§20.5–20.6 pp.1059, 1066Fourier stability, conservative fluxes, implicit solves, multigrid
Lecture8-Matrices (29)§9§§2.3–2.6 pp.48, 56, 61, 65; Chapter 11 p.563Structured solves, eigenproblems, SVD, residuals versus conditioning
Lecture9-PW (20)§10Chapter 11 p.563; §12.1 p.605; §20.7 p.1083Lectures supply Bloch/band physics; the book supports eigensolvers, FFTs, spectral convergence
Lecture10-TransferMatrix (14)§11§1.1 p.8; §2.6 p.65; Chapter 18 p.955Scattering comes from the lecture; conditioning and matching explain thick-barrier failures
Lecture11-MD-Part1-Basics (27)§§12–13§17.4 p.928; Chapter 7 p.340Connect Newtonian evolution and statistical averages; the book is not an MD physics replacement
Lecture11-MD-Part2-setup (40)§§12.4–12.5§7.3 p.361; §17.4 p.928; §21.2 p.1101Initial states, PBC, and neighbor lists from lectures; sampling, integration, and search tools from the book
Lecture11-MD-Part3-forcemodel (36)§§12.2–12.3§5.7 p.229; Chapter 10 p.487Lectures supply force models; derivative checks and optimization test code, not transferability
Lecture11-MD-Part4-ensemble (34)§13§7.3 p.361; §15.8 p.824Ensembles and baths from lectures; sampling and invariant distributions offer a comparison
Lecture11-MD-Part5-analysis (48)§§14, 18§13.2 p.648; §13.4 p.652; §15.1 p.776; §15.4 p.788RDF/MSD/transport from lectures; FFT normalization, spectra, and fitting assumptions extend analysis
Lecture12-MC-Part1-MCMC (24)§§15.1–15.2§7.1 p.341; §15.8 p.824Walks, stationarity, periodicity, mixing; separate equilibrium sampling from growth
Lecture12-MC-Part2-MMC (19)§§15.3–15.4§15.8 p.824Extend Boltzmann Metropolis to asymmetric proposals and posterior sampling
Lecture12-MC-Part3-Ising (20)§16§15.8 p.824; statistical tools in Chapters 14–15Lectures supply the Hamiltonian and critical physics; sampling/statistics support uncertainty analysis
Lecture12-MC-Part4-KMC (23)§17§7.3 p.361; §17.7 p.946Unify with Gillespie networks: total rate, exponential waiting, event choice, dependency graphs

Five connections worth revisiting

Growing errors connect the entire course. Floating-point recurrences, explicit Euler, quantum shooting, and thick-barrier matrices can all amplify unwanted modes. A better representation or algorithm often matters more than extra printed precision.

Quadrature, ODEs, and PDEs share the idea of estimating error before allocating work. Romberg cancels known leading errors, adaptive RK changes steps with local difficulty, and multigrid treats errors at appropriate wavelengths. The methods differ, but each directs work toward what limits accuracy.

Sparsity often comes from physical locality. Difference operators connect nearby points, short-range potentials connect nearby atoms, and a KMC event changes only a few rates. Sparse storage, neighbor lists, and dependency graphs express the same structural advantage.

Equilibrium probabilities and dynamical time must be distinguished. MD has integration time, Metropolis usually has algorithmic steps, and KMC obtains time from specified rates. Methods can share an equilibrium distribution but have different dynamics; matching equilibrium statistics does not establish matching transport.

Independent representations make strong cross-checks. Compare shooting with matrix eigenstates, random walks with diffusion PDEs, MSD with Green–Kubo transport, and exact enumeration with MCMC. These comparisons are less likely to share one hidden mistake than merely changing parameters in the same code.

The book’s C++ implementations, hardware costs, and some practical recommendations reflect its publication period. Modern NumPy/SciPy and specialized simulation software can supply current implementations. Error budgets, conditioning, independent verification, and statistical reasoning remain fundamental to judging their results.

Continue with the Numerical Recipes website, NumPy documentation, SciPy integration documentation, and SciPy linear algebra documentation. For a systematic continuation in MD, Allen and Tildesley’s Computer Simulation of Liquids, second edition, is also among the course references.