Jesper12
- 6
- 1
- Homework Statement
- Hello, for my Physics project I have to make a python code to calculate the magnetic field intensity outside a solenoid that works in a real life scenario. I used the Biot Savart law but I seem to get results that are higher than experimental results and I cant find whats wrong with my code. Does anyone know if someone has ever done this before?
- Relevant Equations
- Biot savart law
Python:
import numpy as np
# Constants
mu_0 = 4 * np.pi * 1e-7 # Vacuum permeability (T m/A)
# Solenoid Parameters
R = 0.007 # Radius of the solenoid (meters)
L = 0.074 # Length of solenoid (meters)
N = 1709 # Number of turns
num_segments = 500 # Increased for better accuracy
I = 1.01 # Current in Amperes
def biot_savart_element(dl, r_vec):
"""
Computes the magnetic field contribution dB from a small current segment using Biot-Savart law.
"""
r_mag = np.linalg.norm(r_vec)
if r_mag < 1e-9: # Avoid division by zero
return np.array([0.0, 0.0, 0.0])
# Compute cross product and magnetic field contribution
dB = (mu_0 * I / (4 * np.pi)) * np.cross(dl, r_vec) / (r_mag**3)
return dB
def total_magnetic_field(x_p, y_p, z_p):
"""
Numerically sums contributions from discrete current elements along the helical solenoid.
"""
B_total = np.array([0.0, 0.0, 0.0])
dz_per_turn = L / N # Vertical spacing per turn
dphi = 2 * np.pi / num_segments # Angular step per segment
for n in range(N): # Loop over turns
z_turn = -L / 2 + n * dz_per_turn # Z-position of the turn
for i in range(num_segments): # Loop over segments in the turn
phi = i * dphi # Angular position of the segment
next_phi = (i + 1) * dphi
# Start and end points of the segment
start = np.array([
R * np.cos(phi),
R * np.sin(phi),
z_turn
])
end = np.array([
R * np.cos(next_phi),
R * np.sin(next_phi),
z_turn
])
dl = end - start # Differential length vector
# Vector from the segment to the observation point
r_vec = np.array([x_p, y_p, z_p]) - start
r_mag = np.linalg.norm(r_vec)
if r_mag < 1e-9: # Avoid division by zero
continue
# Add contribution to total magnetic field
B_total += biot_savart_element(dl, r_vec)
return B_total
# Example: Compute B-field at a point near the solenoid
point = (0.08, 0.125, 0) # Observation point (x, y, z) in meters
B_vector = total_magnetic_field(*point)
B_magnitude = np.linalg.norm(B_vector)
# Convert to microteslas
B_x, B_y, B_z = B_vector * 1e6 # Convert components to microteslas
B_magnitude_microtesla = B_magnitude * 1e6
print(f"Magnetic field at {point}:")
print(f"Vector form: [{B_x:.2f}, {B_y:.2f}, {B_z:.2f}] μT")
print(f"Magnitude: {B_magnitude_microtesla:.2f} μT")
Last edited by a moderator: