STEP-BY-STEP TEACHING CODE

Random walks and diffusion.

We build the calculation in small parts and test each part before continuing. The Python notebook follows the same sequence.

We begin with molecules at the origin on an unbounded two-dimensional lattice. Each step moves one lattice spacing in a cardinal direction. Position is measured in lattice spacings and time in sweeps. One sweep moves every molecule once. Mean-square displacement is the average squared distance from the starting point, in squared lattice spacings. The diffusion coefficient for this convention is 1/4 lattice-spacing squared per sweep.

Python notebook · Python notebook collection

If you would like a similar tutorial in Julia or C, email me with the lesson title and your intended use. I can share a Google Colab notebook with step-by-step explanations and worked examples.

Email: saswata_at_msme.iith.ac.in (replace _at_ with @).

Run notebook cells in order. Extract the complete collection without changing its folder structure: the phase-field lesson imports the original kernel from its parent folder. Use Python with NumPy, Matplotlib and Jupyter,.

Technical details

The download includes installation commands and the actual check report.

How do aimless steps produce diffusion?

We start with a picture and a question. Each panel adds one idea before we turn to the equations, code and checks.

1

One walker, four choices

One walker, four choices: schematic panel 1

There is no preferred direction.

We first allow one lattice step up, down, left or right.

2

Follow one wandering path

Follow one wandering path: schematic panel 2

A path can turn back on itself.

Distance traveled is not the same as displacement from the starting point.

3

Look at many endpoints

Look at many endpoints: schematic panel 3

The center stays near the start, but the cloud widens.

For independent unbiased unit steps, the mean squared displacement grows with the number of steps. The sketch uses seed 714; the notebook keeps its own stated seed.

Panels 1–3 are explanatory schematics. Their scales and illustrative fields do not replace the parameters or numerical results in the notebook. Panel 4 shows the notebook’s recorded result or checks.

The calculation, one step at a time

We show the purpose of each notebook cell beside its code and recorded result. The controls move through those results; they do not execute Python in the browser. The notebook remains available for running or changing the calculation.

Loading the lesson…

Step 1: Set the positions and allowed moves

We first check the move lengths. No boundary rule is applied to the positions: the histogram window used by the complete program is only a display window.

Python

import numpy as np
rng = np.random.default_rng(7)
number = 50000
positions = np.zeros((number, 2), dtype=int)
moves = np.array([[1, 0], [-1, 0], [0, 1], [0, -1]])
assert np.all(np.sum(moves**2, axis=1) == 1)
assert np.all(positions == 0)
print("Molecules:", number)

Step 2: Take one sweep

We choose a direction independently for each molecule. After the first sweep every molecule is exactly one lattice spacing from the origin.

Python

choices = rng.integers(0, 4, number)
positions += moves[choices]
assert np.all(np.sum(positions**2, axis=1) == 1)
print("Mean-square displacement after one sweep:", np.mean(np.sum(positions**2, axis=1)))

Step 3: Measure displacement over many sweeps

The predicted ensemble mean-square displacement equals the sweep count. An individual finite sample fluctuates. We therefore use a stated statistical tolerance instead of requiring exact equality. The seed makes this NumPy run repeatable.

Python

sweep_count = 100
history = [0.0, 1.0]
for sweep in range(2, sweep_count + 1):
    choices = rng.integers(0, 4, number)
    positions += moves[choices]
    history.append(float(np.mean(np.sum(positions**2, axis=1))))
relative_error = abs(history[-1] / sweep_count - 1)
assert relative_error < 0.06
print("Measured:", history[-1], "prediction:", sweep_count)
print("Relative error:", relative_error)

Step 4: Individual motion and spreading

A molecule continues making discrete random steps. Diffusion describes the distribution of many molecules. The mean displacement should be small compared with the root-mean-square distance. The check below is an ensemble check for this seeded example, not a universal bound.

Python

mean_position = positions.mean(axis=0)
root_mean_square_distance = np.sqrt(history[-1])
assert np.linalg.norm(mean_position) < 0.1 * root_mean_square_distance
print("Mean position:", mean_position)
print("Root-mean-square distance:", root_mean_square_distance)

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(sweep_count + 1), history, label="Measured")
ax.plot(range(sweep_count + 1), range(sweep_count + 1), "--", label="Prediction")
ax.set_xlabel("Time (sweeps)")
ax.set_ylabel("Mean-square displacement (lattice spacing squared)")
ax.legend()
plt.show()
Checked result: Step 4: Individual motion and spreading
Result from the executed Python notebook.
Technical details

What we checked

We executed all Python notebook cells in a clean kernel. The checks apply to the short examples shown here. They do not establish grid convergence or reproduce every long simulation.

Return to the code collection