import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class Particle:
def __init__(self, x, y, vx, vy, mass, charge):
self.pos = np.array([float(x), float(y)])
self.vel = np.array([float(vx), float(vy)])
self.acc = np.zeros(2)
self.mass = float(mass)
self.charge = float(charge)
def compute_forces(particles, softening=1e-6):
"""Compute pairwise Coulomb forces and update accelerations."""
for i, p1 in enumerate(particles):
p1.acc = np.zeros(2)
for i in range(len(particles)):
for j in range(i + 1, len(particles)):
p1, p2 = particles[i], particles[j]
dr = p2.pos - p1.pos
dist_sq = np.dot(dr, dr)
inv_r3 = 1.0 / (dist_sq * np.sqrt(dist_sq) + softening)
force_mag_vec = p1.charge * p2.charge * inv_r3 * dr
p1.acc += force_mag_vec / p1.mass
p2.acc -= force_mag_vec / p2.mass
def update(particles, dt):
"""Update velocities and positions using simple Euler integration."""
compute_forces(particles)
for p in particles:
p.vel += p.acc * dt
p.pos += p.vel * dt
# Create particles (random for interesting dynamics)
np.random.seed(42)
N = 30 # Number of particles
particles = []
for _ in range(N):
x = np.random.uniform(-8, 8)
y = np.random.uniform(-8, 8)
vx = np.random.uniform(-0.5, 0.5)
vy = np.random.uniform(-0.5, 0.5)
mass = np.random.uniform(1, 20)
charge = np.random.choice([-1.5, -1, 1, 1.5]) # Varied charges
particles.append(Particle(x, y, vx, vy, mass, charge))
# Prepare visualization
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_xlim(-20, 20)
ax.set_ylim(-20, 20)
ax.set_title("Particle Physics Simulator: Charged Particle Dynamics\n(Coulomb Forces, Point Particles)")
ax.set_facecolor('black')
ax.grid(True, alpha=0.3)
# Precompute fixed colors and sizes
colors = ['red' if p.charge > 0 else 'cyan' for p in particles]
sizes = np.array([p.mass * 30 + 50 for p in particles]) # Size based on mass
# Initial scatter plot
initial_offsets = np.array([p.pos for p in particles])
scat = ax.scatter(initial_offsets[:, 0], initial_offsets[:, 1],
c=colors, s=sizes, edgecolors='white', linewidth=0.5,
alpha=0.8)
dt = 0.02 # Time step
steps_per_frame = 10 # Simulation speed
def init():
scat.set_offsets(np.zeros((len(particles), 2)))
return (scat,)
def animate(frame):
for _ in range(steps_per_frame):
update(particles, dt)
offsets = np.array([p.pos for p in particles])
# Optional: wrap around boundaries to keep particles in view
offsets %= 40
offsets[offsets[:, 0] > 20] -= 40
offsets[offsets[:, 1] > 20] -= 40
offsets[offsets[:, 0] < -20] += 40
offsets[offsets[:, 1] < -20] += 40
scat.set_offsets(offsets)
return (scat,)
# Create and run animation
ani = FuncAnimation(fig, animate, init_func=init, blit=True, interval=30)
plt.tight_layout()
plt.show()
# To save animation: ani.save('particle_physics.gif', writer='pillow', fps=30)
This is a complete, self-contained Python script that simulates charged particles interacting via Coulomb forces (electrostatic repulsion/attraction) in 2D. It uses:
Point particles with mass, charge, position, and velocity.
Accurate force calculation with softening to avoid singularities.
Euler integration for dynamics (simple and effective for this scale).
Matplotlib animation for real-time visualization: red/cyan colors for positive/negative charges, sizes scaled by mass, trails-free but dynamic motion.
Random initial conditions for chaotic, interesting "particle physics"-like behavior (clusters form, orbits, ejections).
Periodic boundaries (subtle wrap-around) to keep action in view.
Run it: Copy-paste into a Python file (e.g., particle_sim.py), ensure numpy and matplotlib are installed (pip install numpy matplotlib), and execute python particle_sim.py. Adjust N, dt, steps_per_frame for experimentation. Uncomment the save line to export a GIF!
For extensions: Add magnetic fields, relativistic effects, or collisions by modifying update().