Simulating Brownian Motion with Dynamic Visualization
The project simulated random walk physics based on normal distribution, leveraging numerical methods and real-time plotting.
Computational Physics Project
Q.E.D.
Introduction
Brownian motion, also known as a random walk, describes the erratic and random movement of particles in a fluid due to collisions with molecules. This project simulates the 2D Brownian motion of a particle using a random walk model based on a normal distribution. The simulation leverages numerical methods and visualizes the path dynamically, offering insights into the physics of stochastic processes.
Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
from IPython.display import display, HTML
# Parameters
= 100 # Number of steps
N = 0.4 # Random distribution tuner; sigma = (delta**2)*dt
delta = 0.2 # Time step
dt = [0], [0] # Initial positions
x, y
# Create figure and axes
= plt.subplots(figsize=(5, 5), dpi=100)
fig, ax = ax.plot([], [], "k-", lw=2, label="Path")
path_line, = ax.plot([], [], "ro", label="Particle")
particle, 0, 0, c="blue", marker="x", label="Origin") # Origin
ax.scatter(-1, 1)
ax.set_xlim(-1, 1)
ax.set_ylim(r"$x$")
ax.set_xlabel(r"$y$")
ax.set_ylabel("Brownian Motion Simulation")
ax.set_title(
ax.legend()
# Update function for animation
def update(frame):
global x, y
= x[-1] + np.random.normal(loc=0, scale=(delta**2) * dt)
x_new = y[-1] + np.random.normal(loc=0, scale=(delta**2) * dt)
y_new
x.append(x_new)
y.append(y_new)
path_line.set_data(x, y)-1], y[-1])
particle.set_data(x[
# Adjust axis limits dynamically
min(x) - 0.1, max(x) + 0.1)
ax.set_xlim(min(y) - 0.1, max(y) + 0.1)
ax.set_ylim(return path_line, particle
# Create the animation
= FuncAnimation(fig, update, frames=N, interval=100, blit=True)
ani
# Save the animation as a GIF
= "brownian_motion.gif"
gif_path =PillowWriter(fps=10))
ani.save(gif_path, writer
# Display the GIF inline
f'<img src="{gif_path}" alt="Brownian Motion Simulation">')) display(HTML(