fork download
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation

def simulate_particle_in_magnetic_field(initial_position, initial_velocity, magnetic_field, time_step, num_steps):
    positions = [initial_position]
    velocities = [initial_velocity]

    for _ in range(num_steps):
        velocity = velocities[-1]
        position = positions[-1]

        # Calculate the acceleration using the Lorentz force equation
        acceleration = np.cross(velocity, magnetic_field)

        # Update the velocity and position using the Euler method
        new_velocity = velocity + acceleration * time_step
        new_position = position + velocity * time_step

        velocities.append(new_velocity)
        positions.append(new_position)

    return np.array(positions), np.array(velocities)

# Constants
initial_position = np.array([0, 0, 0])  # Initial position (x, y, z)
initial_velocity = np.array([1, 0, 0])  # Initial velocity (vx, vy, vz)
magnetic_field = np.array([0, 0, 1])  # Magnetic field (Bx, By, Bz)
time_step = 0.01  # Time step size
num_steps = 100  # Number of simulation steps

# Simulate the particle
positions, velocities = simulate_particle_in_magnetic_field(initial_position, initial_velocity, magnetic_field, time_step, num_steps)

# Create the figure and axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Set up the initial plot
particle, = ax.plot([], [], [], 'ro')

# Set the plot limits
ax.set_xlim3d(-2, 2)
ax.set_ylim3d(-2, 2)
ax.set_zlim3d(-2, 2)

# Animation update function
def update(frame):
    x, y, z = positions[frame]

    # Update the particle's position
    particle.set_data([x], [y])
    particle.set_3d_properties([z])

    return particle,

# Create the animation
ani = animation.FuncAnimation(fig, update, frames=len(positions), interval=100, blit=True)

# Display the animation
plt.show()

Success #stdin #stdout 2.43s 59308KB
stdin
Standard input is empty
stdout
Standard output is empty