Random walk (Python)

Contents

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 0x7faa7397c190>]
_images/c1a18a8b7a7733a6267b65bf24506b0aa97125d68e86de6e0450ce15964d7f7a.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 0x7faa73a4f750>]
_images/ef6a088ac7e7496e424a7a7742c263c44065ccde18efbb5f0ff6d58b408ccd11.png