Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save graysonhead/afe5a20716d910b9ad2e1a47ae47d022 to your computer and use it in GitHub Desktop.

Select an option

Save graysonhead/afe5a20716d910b9ad2e1a47ae47d022 to your computer and use it in GitHub Desktop.
def simulate_car_leapfrog(dt, total_time):
"""Simulate car with Leapfrog integration"""
time = 0
position = 0
# Initialize velocity at half-step back
# Start with a half-step using Euler to bootstrap
velocity_half = 0
accel_init = acceleration_curve(0)
velocity_half = accel_init * (dt / 2)
times = [0]
velocities = [0] # Store full-step velocities for plotting
positions = [0]
while time < total_time:
# Get acceleration at current position/velocity
# Estimate full-step velocity for acceleration calculation
velocity_full = velocity_half + acceleration_curve(velocity_half) * (dt / 2)
accel = acceleration_curve(velocity_full)
# Leapfrog: update velocity at half-step, then position
velocity_half_new = velocity_half + accel * dt
position += velocity_half_new * dt
time += dt
# Store full-step velocity for comparison (average of half-steps)
velocity_full = (velocity_half + velocity_half_new) / 2
times.append(time)
velocities.append(velocity_full)
positions.append(position)
velocity_half = velocity_half_new
return times, velocities, positions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment