Tuesday, 18 March 2025

Brownian Motion Pattern using Python

 


import numpy as np

import matplotlib.pyplot as plt

N=10

T=500

step_size=1

x=np.zeros((N,T))

Y=np.zeros((N,T))

for i in range(1, T):

    angle = 2 * np.pi * np.random.rand(N) 

    x[:, i] = x[:, i-1] + step_size * np.cos(angle)

    y[:, i] = y[:, i-1] + step_size * np.sin(angle)

plt.figure(figsize=(8,6))

for i in range(N):

    plt.plot(x[i],y[i],lw=1.5,alpha=0.7)

plt.scatter(x[:,-1],y[:,-1],c='red',marker='o',label="Final position")

plt.title("Brownian motion pattern")

plt.xlabel("X Position")

plt.ylabel("Y Position")

plt.legend()

plt.grid()

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

NumPy (np): Used for efficient numerical operations, including random number generation and array manipulations.

Matplotlib (plt): Used for plotting and visualizing the Brownian motion paths.

2. Defining Parameters

N = 10   # Number of particles

T = 500  # Number of time steps

step_size = 1  # Step size for each move

N = 10 → The number of particles that will undergo Brownian motion.

T = 500 → The number of time steps, meaning each particle moves 500 times.

step_size = 1 → The fixed distance a particle moves at each time step.

3. Initializing Position Arrays

x = np.zeros((N, T))

y = np.zeros((N, T))

x and y arrays:

These are N × T matrices (10 × 500 in this case), initialized with zeros.

Each row represents a different particle, and each column represents a time step.

Initially, all particles start at (0,0).

4. Simulating Brownian Motion

for i in range(1, T):  # Loop over time steps (excluding the first step)

    angle = 2 * np.pi * np.random.rand(N)  # Generate N random angles (0 to 2π)

    x[:, i] = x[:, i-1] + step_size * np.cos(angle)  # Update x-coordinates

    y[:, i] = y[:, i-1] + step_size * np.sin(angle)  # Update y-coordinates

Breaking it Down

for i in range(1, T):

Loops through T-1 time steps (from 1 to 499) because the initial position (t=0) is at (0,0).

angle = 2 * np.pi * np.random.rand(N)

Generates N random angles between 0 and 2π (full circle) for random movement in any direction.

Updating Particle Positions:

X-direction:

x[:, i] = x[:, i-1] + step_size * np.cos(angle)

The next x-coordinate is determined by adding cos(angle) (step movement in x-direction).

Y-direction:

y[:, i] = y[:, i-1] + step_size * np.sin(angle)

The next y-coordinate is determined by adding sin(angle) (step movement in y-direction).

Since angles are random at each step, particles move in completely unpredictable directions.

5. Plotting the Brownian Motion Paths

plt.figure(figsize=(8, 6))

for i in range(N):  

    plt.plot(x[i], y[i], lw=1.5, alpha=0.7)

plt.figure(figsize=(8, 6)) → Sets the figure size to 8 inches by 6 inches.

for i in range(N): → Loops through each particle (N=10).

plt.plot(x[i], y[i], lw=1.5, alpha=0.7)

Plots each particle’s path using lines.

lw=1.5 → Line width is set to 1.5 for better visibility.

alpha=0.7 → Makes lines slightly transparent for better visualization.

6. Highlighting the Final Positions

plt.scatter(x[:, -1], y[:, -1], c='red', marker='o', label="Final Positions")

plt.scatter(0, 0, c='black', marker='x', label="Starting Point")

Final Positions (x[:, -1], y[:, -1])

plt.scatter(x[:, -1], y[:, -1], c='red', marker='o', label="Final Positions")

Marks the last position of each particle with red circles (o).

Starting Position (0,0)

plt.scatter(0, 0, c='black', marker='x', label="Starting Point")

Marks the starting point with a black ‘X’.

7. Customizing the Plot

plt.title("Brownian Motion of Particles")

plt.xlabel("X Position")

plt.ylabel("Y Position")

plt.legend()

plt.grid()

plt.show()

Title & Labels

plt.title("Brownian Motion of Particles") → Sets the title of the plot.

plt.xlabel("X Position") → Labels the X-axis.

plt.ylabel("Y Position") → Labels the Y-axis.

Legend

plt.legend() → Displays the labels for the final positions and the starting point.

Grid

plt.grid() → Adds a grid for better visualization.

Show Plot

plt.show() → Displays the final plot.


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (96) AI (39) Android (24) AngularJS (1) Api (2) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (191) C (77) C# (12) C++ (83) Course (67) Coursera (249) Cybersecurity (25) Data Analysis (2) Data Analytics (2) data management (11) Data Science (148) Data Strucures (8) Deep Learning (21) Django (16) Downloads (3) edx (2) Engineering (14) Euron (29) Events (6) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (11) Google (36) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (84) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (1022) Python Coding Challenge (454) Python Quiz (106) Python Tips (5) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Python Coding for Kids ( Free Demo for Everyone)