create a simple particle simulation in python
- User
create a simple particle simulation in python
- Assistant
create a simple particle simulation in python
Certainly! Below is a simple particle simulation in Python using matplotlib for visualization. This simulation initializes particles with random positions and velocities within a box and updates their positions over time, making them bounce off the walls of the box.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Simulation parameters
NUM_PARTICLES = 50 # Number of particles
BOX_SIZE = 10.0 # Size of the box (10x10 units)
TIME_STEP = 0.1 # Time step for the simulation
MAX_VELOCITY = 1.0 # Maximum initial velocity
# Initialize particle positions and velocities
np.random.seed(42) # For reproducible results
positions = np.random.uniform(0, BOX_SIZE, (NUM_PARTICLES, 2))
velocities = np.random.uniform(-MAX_VELOCITY, MAX_VELOCITY, (NUM_PARTICLES, 2))
# Set up the plot
fig, ax = plt.subplots(figsize=(6, 6))
scatter = ax.scatter(positions[:, 0], positions[:, 1], s=50, color='blue', edgecolor='k')
ax.set_xlim(0, BOX_SIZE)
ax.set_ylim(0, BOX_SIZE)
ax.set_title('Simple Particle Simulation')
ax.set_xlabel('X Position')
ax.set_ylabel('Y Position')
ax.set_aspect('equal')
# Simulation update function
def update(frame_number):
global positions, velocities
# Update positions based on velocities
positions += velocities * TIME_STEP
# Check for collisions with the walls and reflect velocities
for i in range(NUM_PARTICLES):
for dim in range(2): # Check x and y dimensions
if positions[i, dim] <= 0:
positions[i, dim] = 0
velocities[i, dim] *= -1
elif positions[i, dim] >= BOX_SIZE:
positions[i, dim] = BOX_SIZE
velocities[i, dim] *= -1
# Update scatter plot with new positions
scatter.set_offsets(positions)
return scatter,
# Create animation
ani = animation.FuncAnimation(fig, update, frames=200, interval=50, blit=True)
# Display the simulation
plt.show()
Imports:
numpy is used for numerical operations.matplotlib.pyplot and matplotlib.animation are used for plotting and animating the simulation.Parameters:
NUM_PARTICLES sets the number of particles in the simulation.BOX_SIZE defines the dimensions of the square simulation area.TIME_STEP controls the speed of the simulation.MAX_VELOCITY sets the maximum initial speed of any particle.Initialization:
-MAX_VELOCITY and MAX_VELOCITY in both x and y directions.Plot Setup:
BOX_SIZE.Update Function:
update function is called for each frame of the animation.TIME_STEP.Animation:
FuncAnimation from matplotlib.animation is used to animate the simulation.To run the simulation:
Install Required Libraries:
Make sure you have numpy and matplotlib installed. If not, you can install them using:
pip install numpy matplotlib
Save the Code:
Copy the code into a file named, for example, particle_simulation.py.
Run the Script: Execute the script using Python:
python particle_simulation.py
A window should open displaying the animated particle simulation. You will see particles moving around within the box, bouncing off the walls when they reach the edges.
You can modify the simulation parameters to see different behaviors:
Number of Particles:
Increase or decrease NUM_PARTICLES to simulate more or fewer particles.
Particle Speed:
Adjust MAX_VELOCITY to change the initial speeds of the particles.
Simulation Speed:
Change TIME_STEP or the interval parameter in FuncAnimation to speed up or slow down the animation.
Box Size:
Modify BOX_SIZE to change the size of the simulation area.
Particle Appearance:
Adjust the s, color, and edgecolor parameters in the ax.scatter call to change the size and color of the particles.
Enjoy experimenting with the simulation and observing how changes affect particle dynamics!
Not yet included in a published release.