Chemistry · Advanced

Velocity Verlet dynamics

Written by SignalsLab

Early edition: these lessons are being reviewed.

Content

Summary

Velocity Verlet is a time-reversible, symplectic algorithm for integrating Newton's equations of motion in molecular dynamics. It updates positions with the current velocity and acceleration, then updates velocities with the average of old and new accelerations. It gives excellent long-term energy conservation at the cost of only one force evaluation per step.

Intuition

Imagine a movie of atoms where each frame must be computed from the previous one. A naive Euler step uses only the force at the start of the interval, so errors accumulate and energy drifts upward. Velocity Verlet is smarter: it moves the atoms using the current force, recomputes the force at the new positions, and then kicks the velocity using the average of the two forces. This symmetric treatment makes the trajectory reversible in time and preserves phase-space volume, so the energy does not drift but oscillates around the true value. The method actually follows a slightly modified 'shadow' Hamiltonian almost exactly, which explains the stability over millions of steps.

Key equations

m𝐫¨i=𝐅i=−∇iU(𝐫N)
(1)

Newton's equation of motion with forces from the potential energy surface.

𝐫(t+Δt)=𝐫(t)+𝐯(t)Δt+12𝐚(t)Δt2
(2)

Position update using current velocity and acceleration.

𝐯(t+Δt)=𝐯(t)+12[𝐚(t)+𝐚(t+Δt)]Δt
(3)

Velocity update using the average of old and new accelerations.

E=∑i12mivi2+U(𝐫N)
(4)

Total energy, which should be conserved in NVE dynamics and is used to monitor integrator quality.

Derivation

  1. Start from the Taylor expansion forward: r(t+Δt) = r + vΔt + ½aΔt² + O(Δt³).
  2. Write the same expansion backward: r(t−Δt) = r − vΔt + ½aΔt² −...; adding both gives the Verlet formula r(t+Δt) = 2r(t) − r(t−Δt) + a(t)Δt² + O(Δt⁴).
  3. Velocities are not explicit in this scheme; centered difference gives v(t) = [r(t+Δt) − r(t−Δt)]/(2Δt).
  4. Eliminate r(t−Δt) by using the velocity at t+Δt: v(t+Δt) = v(t) + ½[a(t)+a(t+Δt)]Δt, which is equivalent to Verlet in positions.
  5. Implement as: half-kick v(t+Δt/2)=v(t)+½a(t)Δt; drift r(t+Δt)=r(t)+v(t+Δt/2)Δt; compute a(t+Δt); half-kick v(t+Δt)=v(t+Δt/2)+½a(t+Δt)Δt.
  6. Because kick-drift-kick is a symmetric composition of symplectic maps, the integrator is time-reversible and symplectic, with global error O(Δt²) and bounded energy error.

Worked example

Problem

A 1D harmonic oscillator has m = 1, k = 1 (arbitrary units), with r(0)=1, v(0)=0. Perform one velocity Verlet step with Δt = 0.1.

  1. Initial acceleration: a(0) = −k r/m = −1.
  2. Position: r(0.1) = 1 + 0·0.1 + ½(−1)(0.01) = 0.995.
  3. New acceleration: a(0.1) = −0.995.
  4. Velocity: v(0.1) = 0 + ½(−1 − 0.995)(0.1) = −0.09975.
  5. Check energy: E = ½v² + ½r² = ½(0.009950) + ½(0.990025) = 0.0049750 + 0.4950125 = 0.4999875, versus exact 0.5.

Answer r = 0.995, v = −0.09975; energy 0.49999 versus exact 0.5, a tiny error that oscillates rather than drifts.

Common mistakes

  • Reusing the old acceleration in the velocity update instead of computing the force at the new positions.
  • Evaluating forces twice per step; the force at t+Δt should be stored and reused as a(t) for the next step.
  • Choosing too large a time step; for flexible X–H bonds Δt should be about 1 fs or less unless constraints such as SHAKE are used.
  • Expecting exact energy conservation; the energy fluctuates but should not drift, and drift signals a too-large Δt or discontinuous forces from cutoffs.
  • Applying thermostats or barostats incorrectly and then blaming the integrator for non-conservation.

Animation

Animation coming soon

The animated version of this lesson is being prepared for the web. In the Signals AI app, lessons are drawn step by step.

Code

scene.py(232 lines)
import sys
import numpy as np
from manim import *
from blocks import *


def simulate_verlet(mass, spring_k, dt, steps):
    """
    Simulate a single particle in a harmonic potential using Velocity Verlet.
    x(t+dt) = x(t) + v(t)*dt + 0.5*a(t)*dt^2
    v(t+dt) = v(t) + 0.5*(a(t) + a(t+dt))*dt
    
    Returns: t, x, v arrays.
    """
    t = np.zeros(steps + 1)
    x = np.zeros(steps + 1)
    v = np.zeros(steps + 1)
    
    # Initial conditions
    x[0] = 2.0  # Initial displacement
    v[0] = 0.0  # Start from rest
    
    # Initial acceleration a = -k/m * x
    a = -spring_k / mass * x
    
    for i in range(steps):
        t[i+1] = t[i] + dt
        
        # Update position
        x[i+1] = x[i] + v[i] * dt + 0.5 * a[i] * dt**2
        
        # Calculate new acceleration
        a_new = -spring_k / mass * x[i+1]
        
        # Update velocity
        v[i+1] = v[i] + 0.5 * (a[i] + a_new) * dt
        
        # Update acceleration for next step
        a[i+1] = a_new
        
    return t, x, v


# Parameters
MASS = 1.0
SPRING_K = 4.0  # Stiffness
DT = 0.01
STEPS = 500      # ~5 seconds of simulation at 100Hz
TRACE = simulate_verlet(MASS, SPRING_K, DT, STEPS)

# Theoretical frequency and period for verification
OMEGA = np.sqrt(SPRING_K / MASS)
PERIOD = 2 * np.pi / OMEGA


class Main(Scene):
    def construct(self):
        self.camera.background_color = "#111111"
        
        # Title at top
        TitleCard(self, "Velocity Verlet Dynamics", "Symplectic Integration")
        
        # Layout: Simulation on left, Graph on right
        # Simulation Box
        sim_box = Rectangle(width=4.0, height=3.0, color=C_DIM, stroke_width=2)
        sim_box.to_edge(LEFT, buff=0.5).shift(UP * 0.5)
        
        # Particle
        particle = Circle(radius=0.2, fill_color=C_MAIN, fill_opacity=1)
        particle.move_to(sim_box.get_center())
        
        # Spring (visual representation)
        # We'll draw a zig-zag line from wall to particle
        wall_x = sim_box.get_left()[0] + 0.2
        wall = Line(
            start=[wall_x, sim_box.get_bottom()[1] + 0.2, 0],
            end=[wall_x, sim_box.get_top()[1] - 0.2, 0],
            color=C_DIM
        )
        
        # Spring line object
        spring_line = Line(
            start=[wall_x, sim_box.get_center()[1], 0],
            end=[particle.get_center()[0], sim_box.get_center()[1], 0],
            color=C_ACCENT,
            stroke_width=3
        )
        
        # Labels
        label_sim = Text("Simulation", font_size=24, color=WHITE).next_to(sim_box, UP)
        # Label placed inside the box to avoid overlap with graph
        label_x = MathTex(r"x(t)", font_size=24, color=C_ACCENT).next_to(particle, LEFT, buff=0.1)
        
        # Graph Box
        graph_box = Rectangle(width=6.0, height=3.0, color=C_DIM, stroke_width=2)
        graph_box.to_edge(RIGHT, buff=0.5).shift(UP * 0.5)
        
        # Axes for graph
        axes = Axes(
            x_range=[0, 5, 1],
            y_range=[-2.5, 2.5, 1],
            x_length=5.0,
            y_length=2.5,
            axis_config={"color": C_DIM, "include_tip": False}
        )
        axes.move_to(graph_box.get_center())
        
        # Axis Labels
        x_label = Text("Time (s)", font_size=20, color=WHITE).next_to(axes.x_axis, DOWN)
        y_label = Text("Position", font_size=20, color=WHITE).next_to(axes.y_axis, LEFT)
        
        # Curve object
        curve = axes.plot(
            lambda t: 0, # Placeholder
            x_range=[0, 5],
            color=C_MAIN,
            stroke_width=3
        )
        
        # Add all static elements
        self.add(sim_box, wall, particle, spring_line, label_sim, label_x)
        self.add(graph_box, axes, x_label, y_label, curve)
        
        # Animate initial setup
        self.play(Create(sim_box), Create(wall), FadeIn(particle), FadeIn(spring_line), run_time=1)
        self.play(Create(graph_box), Create(axes), FadeIn(x_label), FadeIn(y_label), run_time=1)
        
        # Equation - placed clearly below title, not overlapping
        eq = MathTex(r"x_{n+1} = x_n + v_n \Delta t + \frac{1}{2} a_n \Delta t^2", font_size=28, color=C_ACCENT)
        eq.to_edge(UP, buff=0.3).shift(DOWN * 0.8) # Shift down to avoid title overlap
        self.play(Write(eq), run_time=1.5)
        
        # Simulation Animation
        # We need to update particle position and spring line, and draw the curve
        
        # Get data
        t_vals = TRACE[0]
        x_vals = TRACE[1]
        
        # Map simulation x to screen coordinates
        # Sim x range approx -2 to 2. Screen sim_box width 4. Center is 0.
        # Scale factor: 1 unit = 1.5 screen units roughly?
        # Let's map x in [-2.5, 2.5] to sim_box width.
        # sim_box center is sim_box.get_center()
        # sim_box width is 4.0.
        # So x_screen = center_x + x_sim * (4.0 / 5.0) ? 
        # Actually, let's just use the axes scaling for consistency if possible, 
        # but the sim box is separate.
        # Let's define a mapping function.
        sim_center_x = sim_box.get_center()[0]
        sim_scale = 1.5  # 1 unit of x = 1.5 units of screen space
        
        def get_sim_pos(x_val):
            return np.array([sim_center_x + x_val * sim_scale, sim_box.get_center()[1], 0])

        def update_particle(mob):
            t_curr = tracker.get_value()
            idx = np.searchsorted(t_vals, t_curr)
            idx = min(idx, len(t_vals) - 1)
            x_val = x_vals[idx]
            pos = get_sim_pos(x_val)
            mob.move_to(pos)
            # Keep label attached to particle
            label_x.next_to(mob, LEFT, buff=0.1)

        def update_spring(mob):
            t_curr = tracker.get_value()
            idx = np.searchsorted(t_vals, t_curr)
            idx = min(idx, len(t_vals) - 1)
            x_val = x_vals[idx]
            pos = get_sim_pos(x_val)
            mob.set_points_as_corners([
                [wall_x, sim_box.get_center()[1], 0],
                pos
            ])
            
        def update_curve(mob):
            t_curr = tracker.get_value()
            idx = np.searchsorted(t_vals, t_curr)
            idx = min(idx, len(t_vals) - 1)
            
            # Get points up to idx
            pts = []
            for i in range(idx + 1):
                pts.append(axes.c2p(t_vals[i], x_vals[i]))
            
            if len(pts) > 1:
                mob.set_points_as_corners(pts)

        tracker = ValueTracker(0)
        
        # Run simulation
        self.play(
            UpdateFromFunc(particle, update_particle),
            UpdateFromFunc(spring_line, update_spring),
            UpdateFromFunc(curve, update_curve),
            run_time=10,
            rate_func=linear
        )
        
        # Final Caption
        StepCaption(self, f"Period T = 2π√(m/k) ≈ {PERIOD:.2f}s. Verlet preserves energy well.")
        self.wait(2)


if __name__ == "__main__" and "--selftest" in sys.argv:
    t, x, v = TRACE
    
    # Check initial conditions
    assert abs(x[0] - 2.0) < 1e-6
    assert abs(v[0] - 0.0) < 1e-6
    
    # Check energy conservation (approximate, Verlet is symplectic)
    # E = 0.5 * m * v^2 + 0.5 * k * x^2
    E_initial = 0.5 * MASS * v[0]**2 + 0.5 * SPRING_K * x[0]**2
    
    # Check energy at several points
    for i in range(0, len(x), 50):
        E_curr = 0.5 * MASS * v[i]**2 + 0.5 * SPRING_K * x[i]**2
        # Energy should be conserved within a small tolerance for Verlet
        assert abs(E_curr - E_initial) < 0.01, f"Energy drift at step {i}: {E_curr} vs {E_initial}"
        
    # Check periodicity
    # Find peaks
    from scipy.signal import find_peaks
    peaks, _ = find_peaks(x, distance=50) # Minimum distance between peaks
    if len(peaks) > 1:
        peak_times = t[peaks]
        period_est = np.mean(np.diff(peak_times))
        assert abs(period_est - PERIOD) < 0.2, f"Period mismatch: {period_est} vs {PERIOD}"
        
    print("ok")

The Manim scene code that draws this lesson's animation in the Signals AI app (Python, Manim Community).

ccBYNC© 2026 SignalsLab. Lesson text shared as is under CC BY-NC 4.0.