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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D
def magnetic_field_loop(x, y, z, R, I): """ Calculate the magnetic field components (Bx, By, Bz) at point (x, y, z) for a circular current loop of radius R carrying current I centered at the origin in the x-y plane. Parameters: x, y, z: coordinates of the point where B-field is calculated (meters) R: radius of the current loop (meters) I: current in the loop (amperes) Returns: tuple: (Bx, By, Bz) magnetic field components in Tesla """ mu0 = 4 * np.pi * 1e-7 r = np.sqrt(x**2 + y**2 + z**2) if r == 0: return (0, 0, 0) factor = mu0 * I * R**2 / (4 * np.pi * (R**2 + r**2)**(3/2)) Bx = factor * 3 * x * z / r**2 By = factor * 3 * y * z / r**2 Bz = factor * (3 * z**2 / r**2 - 1) return (Bx, By, Bz)
R = 0.1 I = 1.0
x = np.linspace(-0.2, 0.2, 20) y = np.linspace(-0.2, 0.2, 20) z = np.linspace(-0.2, 0.2, 20) X, Y, Z = np.meshgrid(x, y, z)
Bx = np.zeros_like(X) By = np.zeros_like(Y) Bz = np.zeros_like(Z)
for i in range(len(x)): for j in range(len(y)): for k in range(len(z)): Bx[i,j,k], By[i,j,k], Bz[i,j,k] = magnetic_field_loop(X[i,j,k], Y[i,j,k], Z[i,j,k], R, I)
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(131) y_mid = len(y)//2 magnitude = np.sqrt(Bx[:,y_mid,:]**2 + Bz[:,y_mid,:]**2) ax1.streamplot(x, z, Bx[:,y_mid,:], Bz[:,y_mid,:], color=magnitude, cmap='viridis') ax1.set_title('Magnetic field lines in XZ-plane (y = 0)') ax1.set_xlabel('x (m)') ax1.set_ylabel('z (m)') ax1.add_patch(plt.Circle((0,0), R, fill=False, color='red'))
ax2 = fig.add_subplot(132) z_axis = np.linspace(-0.2, 0.2, 100) Bz_axis = [magnetic_field_loop(0, 0, z_val, R, I)[2] for z_val in z_axis] ax2.plot(z_axis, Bz_axis) ax2.set_title('Bz along z-axis') ax2.set_xlabel('z (m)') ax2.set_ylabel('Bz (T)') ax2.grid(True)
ax3 = fig.add_subplot(133, projection='3d') skip = 3 ax3.quiver(X[::skip,::skip,::skip], Y[::skip,::skip,::skip], Z[::skip,::skip,::skip], Bx[::skip,::skip,::skip], By[::skip,::skip,::skip], Bz[::skip,::skip,::skip], length=0.05, normalize=True) ax3.set_title('3D magnetic field vectors') ax3.set_xlabel('x (m)') ax3.set_ylabel('y (m)') ax3.set_zlabel('z (m)')
plt.tight_layout() plt.show()
|