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.
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}}.
\]
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.
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.
\]
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.
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.
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.
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()
Model parameters
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()
}
Results
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" )
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" )
Numerical verification
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" )
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" )
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" )
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.
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 ) .
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
Computational environment
Python: 3.11.4
NumPy: 2.4.6
Matplotlib: 3.11.2
Operating system: Darwin
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 .