On this page
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
| Stage | Question | Chapters |
|---|---|---|
| Establish a computational language | How does a number enter a computer? What does error mean? | 1. Computing, 2. Error |
| Learn the basic operators | How do we integrate, sample, and differentiate? | 3. Quadrature, 4. MC integration, 5. Differentiation |
| Solve evolution and boundary problems | How do we compute trajectories, temperature fields, waves, and eigenstates? | 6. ODEs, 7. Boundary problems, 8. PDEs, 9. Matrices |
| Enter quantum materials | How do periodicity and interfaces affect a wavefunction? | 10. Plane waves, 11. Transfer matrices |
| Simulate many particles | How do we construct, advance, and analyze an atomic system? | 12. MD models, 13. Ensembles, 14. Analysis |
| Connect probability and dynamics | How do we sample equilibrium? How do we model rare events? | 15. Markov chains, 16. Ising, 17. KMC |
| Produce a research result | How 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 float64 values requires approximately bytes for its data alone. A dense 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 , set and to obtain . 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.
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 ; a dense linear solve commonly costs . 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
The implicit leading 1 gives 53 significant binary digits, roughly 15–16 decimal digits. Adjacent representable values near 1 are separated by . For rounding to nearest, the usual unit roundoff is . The smallest positive normal number is ; subnormal values extend to , 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:
Absolute tolerance becomes especially important near . Ordinary Python integers have extensible precision; fixed-width NumPy integers can overflow. They are different numerical types.
2.2 Five distinct sources of error
| Source | Example | Response |
|---|---|---|
| Model error | Classical nuclei for low-temperature hydrogen | Improve the physics; compare with experiments or a higher-level model |
| Parameter uncertainty | Uncertain potential parameters or diffusivity | Sensitivity analysis and uncertainty propagation |
| Truncation/discretization | A finite difference replaces a derivative | Converge grids, time steps, and basis cutoffs |
| Roundoff | Subtracting nearby large numbers; long sums | Stable reformulation, suitable precision, careful summation |
| Statistical error | Finite MC samples or MD trajectories | Correlation 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 , computing subtracts nearly equal numbers and can lose most significant digits. The equivalent expression
avoids this cancellation. Similarly, use np.expm1(x) for and np.log1p(x) for when appropriate.
Conditioning describes how sensitive the mathematical problem is to input perturbations. Stability describes how an algorithm amplifies additional errors. For , a local relative condition number is . Large means even a stable algorithm cannot recover high-accuracy answers from low-accuracy inputs.
For , the residual is . A small residual means the approximate solution nearly satisfies the equations. If is ill-conditioned, can nevertheless be far from the true solution. The matrix condition number 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 , halving the step should reduce the leading error by approximately . Without an analytical answer, estimate
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
cancels a leading error term; it is not an independent exact solution.
Experiment: compare the two square-root expressions at . Explain why algebraic equivalence does not imply equivalence in floating-point arithmetic.
3. Numerical integration: from areas to error control
The integral accumulates infinitely many thin strips. Quadrature replaces that limit with a finite set of function evaluations. Let and .
3.1 Rectangles, trapezoids, and Simpson’s rule
The left rectangle rule is generally first order globally. The midpoint rule is second order for sufficiently smooth functions. The composite trapezoid rule is
Replacing a curve by a line on one interval produces an integration error of . There are approximately intervals, giving global error. Simpson’s rule integrates a quadratic interpolant over each pair of intervals and requires even :
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 on , 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 . Thus removes the quadratic term; repeated extrapolation gives Romberg integration. Endpoint nonsmoothness can invalidate this even-power expansion.
Adaptive Simpson integration compares one-interval result with the sum on two halves, estimating the finer result’s error by . 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; nodes integrate polynomials through degree exactly. It is attractive for smooth functions with expensive evaluations, but is not universally better than a uniform grid.
For , evaluating the integrand at zero is impossible. Substitute and include the Jacobian . 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
The laboratory function trap2d gives approximately 0.18393790 with 200 intervals per direction, compared with the exact 0.18393972. Integrating over first provides a short analytical check.
A hundred points per direction requires evaluations in three dimensions and in ten. This motivates Monte Carlo integration. Experiment: compare trapezoid, Simpson, and Gaussian quadrature at equal evaluation counts; then replace the integrand by 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 denotes a sampled outcome. Its probability density satisfies and . The expectation is the target of repeated sample averaging. The variance describes the scatter of individual outcomes.
Draw independent uniform points from . Then
The standard deviation 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 . Its 95% coverage concerns repetitions of the experiment; one realization is not guaranteed to cover the exact answer.
Typical MC error decreases as , 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, ; rejection sampling from an easily sampled envelope; and transformations, such as converting uniform values into normal values. Exponential waiting times can be generated by with . Implementations must handle endpoints; the laboratory uses -np.log1p(-rng.random()) / rate.
4.3 Why importance sampling works
Choose a normalized density that is positive wherever . Then
Uniform sampling wastes work when most of the contribution comes from a small region. Choosing close to can reduce variance. The ideal 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 on , 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 , where the uncertainty is one standard error. The exact answer is . Use independent seeds to compare root-mean-square error at . 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
The forward difference has truncation error. Subtracting expansions at positive and negative steps cancels even powers and gives
Adding them produces a second derivative:
However, the first centered difference divides function-value errors by . Its total error often behaves like . Balancing the terms gives an optimal scale . For the centered second derivative, gives . 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, , 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 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 . 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 and . Newton’s second-order equation can be rewritten as a first-order system:
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 . Its local one-step error is ; its global error over a fixed time interval is usually . For the dimensionless harmonic oscillator,
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
It is globally second order. The position recurrence has an 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 ; 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 below do not include the step size:
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 . Define
For an embedded estimator scaling as , a candidate next step is approximately , 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 , Euler’s amplification factor is , requiring . 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 , 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 , then add drag and braking over a finite interval. Atmospheric density, velocity relative to the atmosphere, and braking times are physical inputs. First recover circular speed without drag, checking energy and angular momentum. Add complexity one term at a time. Ground impact is an event: locate instead of integrating through the Earth. Split integration at nonsmooth force-switching times.
A driven damped pendulum satisfies
Start by verifying the small-angle, undriven limit. Discard transients, inspect phase space, and sample a Poincaré section once per forcing period . 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 has at least one root in . Bisection halves the bracket at every iteration. Continuity is essential: crossing the pole of changes sign without crossing a root. An even-multiplicity root such as does not change sign and can be missed by sign scanning.
Newton’s method,
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 and are known but is not. Set the initial slope to , integrate, and define . Solve . With several unknown starting parameters, the residual becomes a vector and requires a coupled root solve.
For with , the exact solution is 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
becomes with . Energy is adjusted until both boundaries are satisfied. For an infinite well on ,
For the more general equation , the uniform-grid Numerov recurrence is
It uses the differential equation to eliminate higher derivatives from a Taylor expansion. The common description “sixth order” refers to the recurrence residual before division by . 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, , 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
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 introduces two separate errors: a coarse mesh and a small computational box. Refine 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 on , ,
Substituting a Fourier error mode gives amplification factor . Requiring for every mode gives in one dimension. On a multidimensional rectangular grid, require . 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:
For linear constant-coefficient diffusion it is stable at every positive time step and second order in both space and time. However, for large , the amplification of high-frequency modes approaches . 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 , the endpoints are zero, and the initial profile is . The exact solution is . At , maximum errors for 20 and 40 intervals are approximately and , a factor of four apart. The laboratory uses tridiagonal elimination at each step. Its unpivoted implementation is appropriate for these well-behaved matrices, not every tridiagonal system.
For , discretize interface fluxes in instead of replacing it by . 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 , the two-dimensional equal-spacing update target is
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 . For symmetric positive-definite systems, 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 , centered differences give
One-dimensional stability requires ; in multiple dimensions require . Initialize the first step correctly. Given initial displacement and velocity ,
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 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 finds vectors whose direction is preserved by the operator. A Hermitian matrix, , has real eigenvalues and orthogonal eigenvectors for distinct eigenvalues. Use np.linalg.eigh rather than root finding on . Determinants can overflow, suffer cancellation, and make nearby roots difficult to isolate.
With , the oscillator Hamiltonian is . On interior uniform-grid points,
The wavefunction vanishes at the endpoints, which are excluded from the unknown vector. eigh returns vectors with . Continuous normalization requires , so use .
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 under refinement. Also inspect , 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, . The Hamiltonian commutes with lattice translations, giving eigenstates of the form
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 . Projection gives
The differential equation has become a matrix eigenproblem. For a real potential, , so the matrix must be Hermitian. This check detects Fourier-sign, index, and normalization mistakes.
10.2 A calculable band gap
Take period , , and . Only are nonzero, coupling adjacent reciprocal vectors. Without a potential, the energies are folded parabolas . At the zone boundary , two free states are degenerate; a weak-potential two-state approximation predicts a gap .
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 , 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 . The small laboratory example instead fixes an integer reciprocal-vector range to make the matrix transparent. Converge the basis at each , 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 , while FFTs reduce the cost on standard grids to . 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, with . Interfaces normally match the wavefunction and its derivative; the corresponding effective-mass model instead matches and . Textbooks use different propagation directions and amplitude origins, so specify the convention before multiplying matrices.
For constant mass and width , the state propagates from left to right as
For several regions, matrices act in physical propagation order, with the first region’s matrix on the right. At , use the limit to avoid division by zero.
11.2 Transmission is a current ratio
Let the incoming amplitude on the left be 1, the reflected amplitude , and the sole outgoing amplitude on the right . Plane-wave current is . When both leads support propagating channels,
Only equal lead velocities give . For a real, nonabsorbing single-channel potential, 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 , use . Exponential decay inside the barrier does not imply exactly zero transmission. For a rectangular barrier between equal-potential leads and ,
lab.barrier(E=0.5, height=1, width=1) uses and gives , , 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 and . 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 for zero potential and 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 .
12. Molecular dynamics: constructing a physical particle model
12.1 What MD solves
Classical molecular dynamics (MD) advances
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
Short-range repulsion suppresses overlap, while the attractive term models dispersion. , and the minimum at has depth . With ,
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 is commonly imposed. Subtracting makes energy continuous but does not make the force continuous. A force-shifted model uses, for ,
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 and require care for interfaces or strongly nonuniform systems.
12.3 Choose the force model before extending the trajectory
| Model | Main structure | Uses and limits |
|---|---|---|
| LJ, Morse, Buckingham | Pair-distance functions | Noble gases and effective interactions; limited descriptions of bond direction and changing environment |
| Coulomb | Long-range charge interaction | Ionic and polar systems; a simple hard cutoff is usually inadequate, motivating Ewald or particle-mesh treatments |
| EAM | Embedding energy plus pair terms | Metals; depends on a local electron-density surrogate and needs transferability checks |
| Stillinger–Weber | Pair terms and explicit three-body angles | Covalent networks and specific material models |
| Tersoff/Brenner | Environment-dependent bond order | Directional bonding for supported elements and environments |
| MEAM | Embedding framework with angular information | Extended metallic and some more complex bonding environments |
| Molecular force fields | Bonds, angles, torsions, and nonbonded terms | Organic and biological molecules; topology, constraints, and parameter scope matter |
For example, EAM has with . 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
Initialize on a lattice or with a nonoverlapping random arrangement. Maxwell velocities have variance 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 , minimum-image displacement is
The simple minimum-image short-range algorithm requires . 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 ; force evaluation still applies . Rebuild when the largest displacement since construction exceeds . 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 . For transparency, the laboratory’s lj_force uses an 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 . This checks the force/integrator combination; it is not an equilibrated liquid diffusion measurement.
Experiment: integrate the same physical duration with and 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
| Ensemble | Fixed quantities | Typical use |
|---|---|---|
| NVE | Particle number, volume, energy | Isolated systems, integrator checks, suitable dynamical measurements |
| NVT | Particle number, volume, temperature | Equilibrium at fixed temperature |
| NPT | Particle number, pressure, temperature | Density, thermal expansion, structures at fixed pressure |
| VT | Chemical potential, volume, temperature | Particle reservoirs, adsorption, open systems |
The canonical density is , with . 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 effective momentum degrees of freedom,
In three dimensions with center-of-mass motion removed and no other constraints, typically . 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 dimensions,
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
The relation between noise strength and friction establishes thermal equilibrium under suitable conditions. Discrete random increments scale as rather than ; 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 compares local number density around a particle with a homogeneous reference. For an isotropic three-dimensional one-component system, the shell volume is
If each frame counts unordered pairs and their frame-averaged count is , a finite- ideal-gas normalization is
Its expectation is one for a uniform ideal gas. In a simple periodic box, normally restrict . Do not include the factor of two again if counting ordered pairs. In the thermodynamic limit, coordination is often written . With the finite-system normalization above, the corresponding neighbor density is . Here denotes the first minimum after the first peak, not the smallest pair distance.
The structure factor
connects atomic arrangements to scattering. Account for the trivial density contribution at 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
Use continuous unwrapped coordinates across periodic boundaries. For equilibrium isotropic diffusion at long times, , so divide its slope by . Short-time inertial motion is ballistic and scales as ; 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:
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 sets Nyquist frequency ; total duration sets resolution of order . 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 and divides by . 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 , computes each block mean , and estimates SE as the standard deviation of block means divided by the square root of the number of blocks. Increase 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 with equal probability at each step. Then and . If each step takes , comparison with gives . The probability recurrence
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 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 , with each row summing to one. Distributions evolve as ; a stationary distribution satisfies .
Detailed balance,
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 , propose using and accept with
The product equals the smaller of the forward and reverse weights. It is unchanged under exchanging and , establishing detailed balance. Unknown normalization cancels in the ratio.
For canonical configurations, , a symmetric proposal gives . 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:
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 , a common convention is
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, . 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 , with energy
Count each nearest-neighbor bond once. Flipping a spin changes only its four adjacent bonds and field term, giving
At zero field, , so acceptance factors can be precomputed. Choose a random site, calculate its local energy change, and accept using Metropolis. 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 and magnetization per spin . Heat capacity and susceptibility per spin are
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 , so often displays ordering more clearly. Replacing by inside the susceptibility formula silently defines a different observable and must be distinguished.
For the infinite, zero-field, nearest-neighbor ferromagnetic square-lattice model,
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 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 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 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 . 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
A rate has inverse-time units. 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 and total rate . Survival over a short interval is approximately , giving and . Therefore,
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 , 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- exponential waiting time.
17.3 Weight averages by residence time
If state persists for ,
Consider with , . Events alternate, so event counts assign half the observations to each state. But the mean residence is 1/2 time unit in and one unit in , giving stationary occupations . lab.kmc_two_state() gives approximately . 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 with independent normal errors of known standard deviation , maximum likelihood minimizes
Correlated errors require a residual vector and covariance : . 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: 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
- Model definition: equations, units, boundaries, potential parameters, ensemble, and observable.
- Benchmarks: analytical limits, exact enumeration, or an independent numerical method.
- Numerical convergence: separate changes to time step, mesh, box, basis, and cutoff.
- Statistical reliability: equilibration, correlation times, effective sample counts, independent repetitions, and error bars.
- Reproducibility: inputs, seeds, software versions, code version, raw data, and plotting scripts.
- 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
| Problem | Reasonable starting point | Additional checks |
|---|---|---|
| Smooth one-dimensional integral | Adaptive or Gaussian quadrature | Singularities, narrow peaks, absolute tolerance |
| High-dimensional integral | MC, importance sampling, randomized quasi-MC | Weight variance and uncertainty assumptions |
| Nonstiff initial value problem | Adaptive RK | Events, scales, observable convergence |
| Long conservative dynamics | Suitable symplectic integration | Time step, energy, and phase |
| Stiff initial value problem | Implicit methods | Jacobian, nonlinear solves, accuracy |
| Linear system | Structure-aware factorization or iteration | Conditioning, residuals, preconditioning |
| Hermitian eigenproblem | eigh or a suitable sparse solver | Orthogonality, residuals, basis/grid |
| Elliptic PDE | Multigrid or preconditioned sparse methods | Boundary compatibility, discretization error |
| Equilibrium statistics | MD or MCMC | Ensemble, ergodicity, correlation |
| Rare-event dynamics | KMC with physical rates | Event 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.
| Day | Study and implementation | Evidence to retain |
|---|---|---|
| 1 | Environment, variables, arrays, loops, functions | Run the laboratory; explain files, terminal, and interpreter |
| 2 | Units, nondimensionalization, memory, complexity | Scale the oscillator and estimate matrix storage |
| 3 | Floating point, cancellation, conditioning | Compare square-root expressions and identify errors |
| 4 | Trapezoid, Simpson, Taylor expansion | An integration error table and second/fourth-order ratios |
| 5 | Romberg, adaptivity, Gaussian rules, singularities | Compare performance on smooth and cornered functions |
| 6 | MC integration, seeds, standard error | Error versus sample size across independent seeds |
| 7 | Importance sampling and differentiation | A derivative-error table or plot; first-week review |
| 8 | Euler, Euler–Cromer, Verlet | Energy and phase for the same oscillator |
| 9 | RK4, adaptivity, stiffness | Short-time order and an explanation of stiff stability limits |
| 10 | Satellite or driven pendulum | One verified limit and one nontrivial trajectory |
| 11 | Bisection, Newton, Brent, shooting | A simple boundary solution and residual |
| 12 | Numerov, quantum boundaries, matching | Three well energies and mesh convergence |
| 13 | Explicit/CN diffusion, tridiagonal solves | Sine-mode decay errors and a deliberately violated stability limit |
| 14 | Poisson, waves, boundaries | Residual for a known field and a correctly initialized wave |
| 15 | Linear systems and Hermitian eigenproblems | Oscillator energies, orthogonality, and box-size checks |
| 16 | Bloch, plane waves, Fourier analysis | Free-particle limit and periodic-potential gap |
| 17 | Transfer matrices, current, conditioning | Transmission curve and check |
| 18 | MD potentials, reduced units, initialization | Two-atom force and energy-gradient agreement |
| 19 | Verlet, PBC, neighbor lists | NVE time-step convergence and total momentum |
| 20 | Ensembles, temperature, pressure, thermostats | Degree-of-freedom accounting and thermostat suitability |
| 21 | RDF, MSD, correlation, blocking | A structural indicator and a dynamical estimate with uncertainty |
| 22 | Random walks, self avoidance, DLA | Verify and explain sampling bias |
| 23 | Markov chains, balance, Metropolis | Stationarity in a two-state chain or small system |
| 24 | Ising and correlation time | Initial-state agreement, blocking, temperature scan |
| 25 | KMC and Gillespie | Two-state residence fractions and uniform rate rescaling |
| 26 | Select a project and its error budget | One-page research design and minimal benchmark |
| 27 | Implement and cross-check | Analytical limit or comparison with a second method |
| 28 | Numerical and statistical convergence | At least three key resolutions and independent repetitions |
| 29 | Fit, plot, and interpret | Figures with units and visible uncertainties; parameter table |
| 30 | Rerun and write a report | A 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 , 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.
| Check | Result or target |
|---|---|
| Trapezoid and Simpson error ratios | 3.999875, 15.996427 |
| Verlet and RK4 endpoint error ratios | 4.002913, 15.998809 |
| Two-dimensional integral | 0.18393790, approaching |
| Scalar root | 0.73908513325 |
| Numerov sine-solution maximum error | Approximately |
| Heat-equation mesh error ratio | Approximately 4.0006 |
| First four oscillator energies | 0.499862, 1.499311, 2.498208, 3.496553 |
| First cosine-potential band gap | Approximately 0.198025; weak-potential estimate 0.2 |
| Rectangular barrier | , to roundoff |
| Short MD trajectory | Maximum energy change per atom approximately |
| Ising local energy differences | All 4,608 flips agree with full energy differences |
| Two-state KMC residence fractions | Approximately 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 file | Tutorial | Third-edition correspondence and starting pages | Main insight from comparison |
|---|---|---|---|
| Lecture0 (10 pages) | Roadmap, §§1, 19 | Chapter 1, p.1 | Computation as a loop of modeling, algorithms, and verification |
| Lecture1-introduction (21) | §§1–2 | §1.1 p.8; §22.2 p.1163 | Extend computer/programming foundations to representation error and stability |
| Lecture2-ErrorAnalysis (19) | §§2, 5 | §1.1 p.8; §5.7 p.229 | Propagation, 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.194 | From 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, 410 | Sampling transformations, standard errors, importance/stratified/quasi-MC distinctions |
| Lecture5-Differentiation (15) | §5 | §5.7 p.229; §14.9 p.766 | Truncation versus roundoff and local fits for noisy data |
| Lecture6-ODE-I (25) | §6 | §§17.1–17.2 pp.907, 910; §17.4 p.928 | Local/global error, cost comparisons, adaptivity, conservative second-order systems |
| Lecture6-ODE-II (26) | §6.5 | §§17.1–17.2; §17.5 p.931 | Satellites, 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, 964 | Root 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, 1066 | Fourier stability, conservative fluxes, implicit solves, multigrid |
| Lecture8-Matrices (29) | §9 | §§2.3–2.6 pp.48, 56, 61, 65; Chapter 11 p.563 | Structured solves, eigenproblems, SVD, residuals versus conditioning |
| Lecture9-PW (20) | §10 | Chapter 11 p.563; §12.1 p.605; §20.7 p.1083 | Lectures 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.955 | Scattering 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.340 | Connect 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.1101 | Initial 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.487 | Lectures supply force models; derivative checks and optimization test code, not transferability |
| Lecture11-MD-Part4-ensemble (34) | §13 | §7.3 p.361; §15.8 p.824 | Ensembles 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.788 | RDF/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.824 | Walks, stationarity, periodicity, mixing; separate equilibrium sampling from growth |
| Lecture12-MC-Part2-MMC (19) | §§15.3–15.4 | §15.8 p.824 | Extend Boltzmann Metropolis to asymmetric proposals and posterior sampling |
| Lecture12-MC-Part3-Ising (20) | §16 | §15.8 p.824; statistical tools in Chapters 14–15 | Lectures supply the Hamiltonian and critical physics; sampling/statistics support uncertainty analysis |
| Lecture12-MC-Part4-KMC (23) | §17 | §7.3 p.361; §17.7 p.946 | Unify 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.