Skip to main content

Numerical Integration of the Harmonic Oscillator

Accuracy, stability and energy conservation

Comparing Euler, Euler-Cromer and velocity Verlet integration through analytical verification and numerical convergence.
Computational Physics
Numerical Methods
Classical Mechanics
Author

Colton Wardle

Published

November 22, 2026

1 Abstract

This investigation compares three numerical integration methods applied to the classical harmonic oscillator: explicit Euler, Euler-Cromer and velocity Verlet.

The methods are evaluated through comparison with the analytical solution, mechanical energy conservation and numerical convergence.

2 Physical background

The classical harmonic oscillator describes a system experiencing a restoring force proportional to its displacement.

Hooke’s law gives

\[ F=-kx. \]

Combining this with Newton’s second law gives

\[ m\frac{d^2x}{dt^2}+kx=0 \tag{1}\]

where \(m\) is mass and \(k\) is spring stiffness.

The natural angular frequency is

\[ \omega=\sqrt{\frac{k}{m}}. \]

3 Analytical solution

For arbitrary initial displacement and velocity,

\[ x(t)=x_0\cos(\omega t) +\frac{v_0}{\omega}\sin(\omega t). \]

This solution provides a reference against which the numerical methods can be evaluated.

4 Numerical methods

The governing equation can be expressed as two first-order differential equations:

\[ \frac{dx}{dt}=v \]

\[ \frac{dv}{dt}=-\frac{k}{m}x. \]

4.1 Explicit Euler

\[ x_{n+1}=x_n+h v_n \]

\[ v_{n+1}=v_n+h a_n \]

The explicit Euler method is first-order accurate but artificially increases the energy of an ideal harmonic oscillator.

4.2 Euler-Cromer

\[ v_{n+1}=v_n+h a_n \]

\[ x_{n+1}=x_n+h v_{n+1} \]

Updating velocity before displacement improves the long-term energy behavior.

4.3 Velocity Verlet

\[ x_{n+1}=x_n+h v_n+\frac{1}{2}h^2a_n \]

\[ v_{n+1}=v_n+\frac{h}{2}(a_n+a_{n+1}) \]

Velocity Verlet is second-order accurate and is widely used in molecular dynamics.

5 Computational implementation

Show source code
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path

from model import (
    analytical_solution,
    euler,
    euler_cromer,
    velocity_verlet,
    total_energy,
    rms_error
)

Path("figures").mkdir(exist_ok=True)

plt.rcParams.update({
    "figure.dpi": 150,
    "axes.spines.top": False,
    "axes.spines.right": False,
    "axes.grid": True,
    "grid.alpha": 0.2,
    "font.size": 11,
    "lines.linewidth": 2
})

methods = {
    "Euler": euler,
    "Euler-Cromer": euler_cromer,
    "Velocity Verlet": velocity_verlet
}

colors = {
    "Euler": "#c65d55",
    "Euler-Cromer": "#d29b57",
    "Velocity Verlet": "#387e7a"
}

def finish_figure(fig, filename):
    fig.tight_layout()
    fig.savefig(
        f"figures/{filename}.png",
        dpi=150,
        bbox_inches="tight"
    )
    plt.show()

5.1 Model parameters

Parameter Value
Mass 1 kg
Spring constant 4 N/m
Initial displacement 1 m
Initial velocity 0 m/s
Timestep 0.05 s
Duration 10 s
Show source code
m = 1.0
k = 4.0
x0 = 1.0
v0 = 0.0
dt = 0.05
duration = 10.0

steps = round(duration / dt)
t = np.linspace(0, duration, steps + 1)

x_exact, v_exact = analytical_solution(
    t, x0, v0, m, k
)

solutions = {
    name: method(t, x0, v0, m, k)
    for name, method in methods.items()
}

6 Results

6.1 Displacement

Show source code
fig, ax = plt.subplots()

ax.plot(
    t, x_exact,
    color="#777777",
    linestyle="--",
    label="Analytical"
)

for name, (x, v) in solutions.items():
    ax.plot(
        t, x,
        color=colors[name],
        label=name
    )

ax.set_xlabel("Time (s)")
ax.set_ylabel("Displacement (m)")
ax.legend()

finish_figure(fig, "displacement")
Figure 1: Comparison of numerical and analytical displacement.

6.2 Phase space

Show source code
fig, ax = plt.subplots()

ax.plot(
    x_exact, v_exact,
    color="#777777",
    linestyle="--",
    label="Analytical"
)

for name, (x, v) in solutions.items():
    ax.plot(
        x, v,
        color=colors[name],
        label=name
    )

ax.set_xlabel("Displacement (m)")
ax.set_ylabel("Velocity (m/s)")
ax.legend()

finish_figure(fig, "phase-space")
Figure 2: Phase-space trajectories for the numerical integration methods.

7 Numerical verification

7.1 Displacement error

Show source code
fig, ax = plt.subplots()

for name, (x, v) in solutions.items():
    ax.plot(
        t,
        np.abs(x - x_exact),
        color=colors[name],
        label=name
    )

ax.set_xlabel("Time (s)")
ax.set_ylabel("Absolute error (m)")
ax.legend()

finish_figure(fig, "error")
Figure 3: Absolute displacement error relative to the analytical solution.

7.2 Mechanical energy

The total mechanical energy is

\[ E=\frac{1}{2}mv^2+\frac{1}{2}kx^2. \]

For the ideal harmonic oscillator, this quantity should remain constant.

Show source code
fig, ax = plt.subplots()

ax.axhline(
    1,
    color="#777777",
    linestyle="--",
    label="Exact energy"
)

for name, (x, v) in solutions.items():
    energy = total_energy(x, v, m, k)

    ax.plot(
        t,
        energy / energy[0],
        color=colors[name],
        label=name
    )

ax.set_xlabel("Time (s)")
ax.set_ylabel("Normalized energy")
ax.legend()

finish_figure(fig, "energy")
Figure 4: Normalized mechanical energy as a function of time.

7.3 Convergence analysis

For a numerical method of order \(p\),

\[ \epsilon(h)\approx Ch^p. \]

The convergence order can be estimated from the slope of a logarithmic plot of numerical error against timestep.

Show source code
step_counts = np.array([
    200, 400, 800, 1600,
    3200, 6400, 12800
])

timesteps = duration / step_counts
orders = {}

fig, ax = plt.subplots()

for name, method in methods.items():
    errors = []

    for n in step_counts:
        times = np.linspace(
            0, duration, n + 1
        )

        exact, _ = analytical_solution(
            times, x0, v0, m, k
        )

        numerical, _ = method(
            times, x0, v0, m, k
        )

        errors.append(
            rms_error(numerical, exact)
        )

    errors = np.array(errors)

    order = np.polyfit(
        np.log(timesteps[-4:]),
        np.log(errors[-4:]),
        1
    )[0]

    orders[name] = order

    ax.loglog(
        timesteps,
        errors,
        marker="o",
        color=colors[name],
        label=f"{name} (p={order:.2f})"
    )

ax.set_xlabel("Timestep (s)")
ax.set_ylabel("RMS displacement error (m)")
ax.legend()

finish_figure(fig, "convergence")
Figure 5: Measured numerical convergence of the integration methods.

7.4 Quantitative comparison

Table 1: Quantitative comparison of numerical integration methods.
Method RMS error (m) Max. relative energy error Measured order
Euler 6.364e-01 6.316e+00 1.020
Euler-Cromer 3.798e-02 5.262e-02 1.004
Velocity Verlet 3.329e-03 2.500e-03 2.000

8 Discussion

The explicit Euler method introduces artificial energy growth into the harmonic oscillator.

Euler-Cromer improves energy behavior through a different ordering of the state updates.

Velocity Verlet combines second-order accuracy with bounded energy deviations for sufficiently small fixed timesteps.

These results illustrate why numerical method selection must account for physical consistency in addition to computational accuracy.

9 Conclusion

Numerical methods that solve the same governing equations can exhibit substantially different accuracy and long-term physical behavior.

Analytical comparison, energy analysis and convergence testing provide complementary approaches to numerical verification.

For further discussion of numerical integration methods, see Hairer et al. (2006).

10 Reproducibility

The numerical algorithms are separated from the article and verified using automated tests.

From the project root, execute:

python -m pytest posts/001-harmonic-oscillator/test_model.py -v

10.1 Computational environment

Python: 3.11.4
NumPy: 2.4.6
Matplotlib: 3.11.2
Operating system: Darwin

11 References

Hairer, Ernst, Christian Lubich, and Gerhard Wanner. 2006. Geometric Numerical Integration: Structure-Preserving Algorithms for Ordinary Differential Equations. 2nd ed. Springer. https://doi.org/10.1007/3-540-30666-8.