Last active
November 1, 2021 06:44
-
-
Save mick001/5c805433046fa31aec36 to your computer and use it in GitHub Desktop.
Biot-Savart law: magnetic field of a straight wire, Python simulation. Full article at: http://www.firsttimeprogrammer.blogspot.com/2015/05/biot-savart-law-magnetic-field-of.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from mpl_toolkits.mplot3d import axes3d | |
import matplotlib.pyplot as plt | |
import numpy as np | |
x = np.linspace(-4,4,10) | |
y = np.linspace(-4,4,10) | |
z = np.linspace(-4,4,10) | |
x,y,z = np.meshgrid(x,y,z) | |
# 3d figure | |
fig = plt.figure() | |
ax = fig.gca(projection='3d') | |
def B(x,y): | |
i = 1 #Amps in the wire | |
mu = 1.26 * 10**(-6) #Magnetic constant | |
mag = (mu/(2*np.pi))*(i/np.sqrt((x)**2+(y)**2)) #Magnitude of the vector B | |
by = mag * (np.cos(np.arctan2(y,x))) #By | |
bx = mag * (-np.sin(np.arctan2(y,x))) #Bx | |
bz = z*0 #Bz (zero, using the right-hand rule) | |
return bx,by,bz | |
def cylinder(r): | |
phi = np.linspace(-2*np.pi,2*np.pi,100) | |
x = r*np.cos(phi) | |
y = r*np.sin(phi) | |
return x,y | |
# Plot of the fields | |
bx,by,bz = B(x,y) #Magnetic field | |
cx,cy = cylinder(0.2) #Wire | |
# Plot of the 3d vector field | |
ax.quiver(x,y,z,bx,by,bz,color='b',length=1,normalize=True) | |
#Plot the magnetic field | |
for i in np.linspace(-4,4,800): #Plot the wire | |
ax.plot(cx,cy,i,label='Cylinder',color='r') | |
plt.title('Magnetic field of a straight wire') | |
plt.xlabel('x') | |
plt.ylabel('y') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi!
This is a really nice and clear starting point for beginners who wish to simulate the magnetic field of simple conductors.
I have also started with a small program like this, using Matplotlib for visualization.
But with increasing complexity, Matplotlib has gotten way too slow, and I switched over to VisPy which has OpenGL support.
Now, very recently I released a full-fledged Python-powered GUI for magnetic field calculation of arbitrary loops of wire.
I would appreciate it if you had a look at it. I am still looking for contributors to the project!
Link to my GitHub repo: https://github.com/shredEngineer/MagnetiCalc/
BTW: This is not spam, I really think you'll like it. :-)
Best wishes from Germany