fork download
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from mpl_toolkits.mplot3d import Axes3D
  4. import matplotlib.animation as animation
  5.  
  6. def simulate_particle_in_magnetic_field(initial_position, initial_velocity, magnetic_field, time_step, num_steps):
  7. positions = [initial_position]
  8. velocities = [initial_velocity]
  9.  
  10. for _ in range(num_steps):
  11. velocity = velocities[-1]
  12. position = positions[-1]
  13.  
  14. # Calculate the acceleration using the Lorentz force equation
  15. acceleration = np.cross(velocity, magnetic_field)
  16.  
  17. # Update the velocity and position using the Euler method
  18. new_velocity = velocity + acceleration * time_step
  19. new_position = position + velocity * time_step
  20.  
  21. velocities.append(new_velocity)
  22. positions.append(new_position)
  23.  
  24. return np.array(positions), np.array(velocities)
  25.  
  26. # Constants
  27. initial_position = np.array([0, 0, 0]) # Initial position (x, y, z)
  28. initial_velocity = np.array([1, 0, 0]) # Initial velocity (vx, vy, vz)
  29. magnetic_field = np.array([0, 0, 1]) # Magnetic field (Bx, By, Bz)
  30. time_step = 0.01 # Time step size
  31. num_steps = 100 # Number of simulation steps
  32.  
  33. # Simulate the particle
  34. positions, velocities = simulate_particle_in_magnetic_field(initial_position, initial_velocity, magnetic_field, time_step, num_steps)
  35.  
  36. # Create the figure and axes
  37. fig = plt.figure()
  38. ax = fig.add_subplot(111, projection='3d')
  39.  
  40. # Set up the initial plot
  41. particle, = ax.plot([], [], [], 'ro')
  42.  
  43. # Set the plot limits
  44. ax.set_xlim3d(-2, 2)
  45. ax.set_ylim3d(-2, 2)
  46. ax.set_zlim3d(-2, 2)
  47.  
  48. # Animation update function
  49. def update(frame):
  50. x, y, z = positions[frame]
  51.  
  52. # Update the particle's position
  53. particle.set_data([x], [y])
  54. particle.set_3d_properties([z])
  55.  
  56. return particle,
  57.  
  58. # Create the animation
  59. ani = animation.FuncAnimation(fig, update, frames=len(positions), interval=100, blit=True)
  60.  
  61. # Display the animation
  62. plt.show()
  63.  
  64.  
Success #stdin #stdout 2.43s 59308KB
stdin
Standard input is empty
stdout
Standard output is empty