Wednesday, 20 May 2015

Biot-Savart law: magnetic field of a straight wire

Magnetism and magnetism related phenomena are fascinating almost for everyone, in fact, I remember being a intrigued by the interaction between magnets since I was a little kid. On the other side, Python is great for plotting vector fields, although now that I am using also Matlab I found out most functions in numpy and matlab are similar to those used in Matlab (I don’t know who got inspired by who though).

Here is a small sketch of a vector field. Remember the Biot-Savart law for a straight infinitely long wire, which (assuming the current is flowing upwards) looks something like this:

clip_image002

Below is a 3d representation of the vector field and the Python code used to generate it. The tricky part (if I’m allowed to say so) is that you need to convert the value of the vector field from cylindrical coordinates into cartesian coordinates in order to plot it. Perhaps there’s a way to plot a vector field using also spherical and cylindrical coordinates however I still do not know how to do that.

figure_1

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()

Hope this was interesting! :)

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Thanks for contributing with the fix! I must have deleted the "normalize=True" option somehow!

      Delete
  2. This comment has been removed by the author.

    ReplyDelete