Random walk (Python)#
2D random walk#
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from numpy.random import default_rng
rng = default_rng()
# Parameters
N_PARTICLES = 100
N_STEPS = 10000
STEP_SIZE = 1
CHOICES = np.array([[0, 1], [1, 0], [0, -1], [-1, 0]]) # Up, right, down, and left
dx = CHOICES[rng.integers(4, size=(N_STEPS, N_PARTICLES))]
pos = dx.cumsum(axis=0) - dx[0, :, :]
fig, ax = plt.subplots(figsize=(10, 10))
ax.plot(pos[:, 0, 0], pos[:, 0, 1])
ax.plot(pos[:, 1, 0], pos[:, 1, 1])
[<matplotlib.lines.Line2D at 0x7fd24c10c910>]
Mean-squared displacement (MSD)
fig, ax = plt.subplots(figsize=(10, 10))
msd = np.mean(np.sum(pos**2, axis=1), axis=1)
ax.plot(np.arange(N_STEPS), msd)
[<matplotlib.lines.Line2D at 0x7fd24c1325d0>]