I am trying to write a Python program to simulate two electrons interacting with one another, with only the Couloumb force acting upon them. So, they should be moving in paths that are collinear with one another, but for some reason, my simulated electrons are moving in paths that are parallel to one another.
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 20 10:01:24 2023
@author: sanat
"""
import pygame
import sys
import math
# Constants
WIDTH, HEIGHT = 2000, 1000
BACKGROUND_COLOR = (255, 255, 255)
ELECTRON_RADIUS = 5
TIME_STEP = 0.01 # Time step for simulation
# Electron properties
electron1 = {
"pos": [400, 500],
"velocity": [0, 0],
"charge": - 1.0,
"mass": 1.0
}
electron2 = {
"pos": [900, 600],
"velocity": [0, 0],
"charge": -1.0,
"mass": 1.0
}
# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Electron Motion Simulation")
def calculate_force(e1, e2):
k = 8.988e9 # Coulomb's constant
r = math.sqrt((e1["pos"][0] - e2["pos"][0]) ** 2 + (e1["pos"][1] - e2["pos"][1]) ** 2)
force = (k * e1["charge"] * e2["charge"]) / (r ** 2)
return force
def update_velocity(electron, force):
acceleration = force / electron["mass"]
electron["velocity"][0] += acceleration * TIME_STEP
electron["velocity"][1] += acceleration * TIME_STEP
def update_position(electron):
electron["pos"][0] += electron["velocity"][0] * TIME_STEP
electron["pos"][1] += electron["velocity"][1] * TIME_STEP
def draw_electrons():
for electron in [electron1, electron2]:
pygame.draw.circle(screen, (0, 0, 0), (int(electron["pos"][0]), int(electron["pos"][1])), ELECTRON_RADIUS)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Calculate force between electrons
force = calculate_force(electron1, electron2)
# Update velocities and positions
update_velocity(electron1, force)
update_velocity(electron2, -force) # Opposite force on electron2
update_position(electron1)
update_position(electron2)
# Clear the screen
screen.fill(BACKGROUND_COLOR)
# Draw electrons
draw_electrons()
pygame.display.flip()
pygame.time.delay(1000)
pygame.quit()
sys.exit()
So, that is the code that I have, and I am not quite sure where I have gone wrong.
Thanks to Karl, I was able to fix the code. I was missing a way to find the direction of the force vectors, and was able to resolve like so:
def calculate_force_vector(e1, e2):
k = 8.988e9 # Coulomb's constant
r_vector = np.array(e1["pos"]) - np.array(e2["pos"])
r_magnitude = np.linalg.norm(r_vector)
force_magnitude = (k * e1["charge"] * e2["charge"]) / (r_magnitude ** 2)
force_direction = r_vector / r_magnitude # Normalize the direction vector
force_vector = force_magnitude * force_direction
return force_vector
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With