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>]
_images/0c1268895e03c255ec4f1c7b6443f3ff64f4d08fa73728ec25f17745fc30af94.png

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>]
_images/785b0c9cbcd873346e6ea1f0c85fb78ed1baa51f988a21f424c45ae1f191af08.png