-
Notifications
You must be signed in to change notification settings - Fork 1
/
electric_field.py
60 lines (49 loc) · 2.06 KB
/
electric_field.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import numpy as np
import matplotlib.pyplot as plt
# Define charges: (charge in Coulombs, (x_position, y_position))
charges = [
(1e-1, (0, 0)), # A positive charge at the origin
(-1e-1, (0.008, 0.0)), # A negative charge at x=0.1, y=0.1
# Add more charges as needed
]
# Constants
epsilon_0 = 8.854187817e-12 # Vacuum permittivity in F/m
# Grid setup
x = np.linspace(-0.1, 0.1, 200) # Adjust these limits and resolution as needed
y = np.linspace(-0.1, 0.1, 200)
X, Y = np.meshgrid(x, y)
# Initialize electric field components
Ex, Ey = np.zeros(X.shape), np.zeros(Y.shape)
# Calculate the electric field contribution from each charge
for charge, (x_pos, y_pos) in charges:
dx = X - x_pos
dy = Y - y_pos
r_squared = dx**2 + dy**2
r_hat = np.sqrt(r_squared)
Ex_contribution = charge * dx / (r_squared * r_hat)
Ey_contribution = charge * dy / (r_squared * r_hat)
Ex += Ex_contribution / (4 * np.pi * epsilon_0)
Ey += Ey_contribution / (4 * np.pi * epsilon_0)
# Assuming Ex and Ey are your electric field components
# Calculate the magnitude of the electric field
E_magnitude = np.sqrt(Ex**2 + Ey**2)
# Normalize the electric field components to get unit vectors
Ex_unit = Ex / E_magnitude
Ey_unit = Ey / E_magnitude
# Define your desired range for the magnitudes
min_magnitude, max_magnitude = 0, 1
# Apply a scaling function to adjust magnitudes into the desired range
# Here's a simple linear rescaling, assuming you've calculated E_magnitude_min and E_magnitude_max beforehand
E_magnitude_rescaled = (
min_magnitude + (E_magnitude - E_magnitude.min()) / (E_magnitude.max() - E_magnitude.min()) *
(max_magnitude - min_magnitude)
)
# Use the rescaled magnitudes with unit direction vectors for plotting
Ex_display = Ex_unit * E_magnitude_rescaled
Ey_display = Ey_unit * E_magnitude_rescaled
plt.figure(figsize=(12, 7))
plt.quiver(X, Y, Ex_display, Ey_display, scale=3, color='red') # Adjust scale for better visualization
plt.xlabel('X position (m)')
plt.ylabel('Y position (m)')
plt.title('Electric Field Due to Multiple Charges')
plt.show()