DEV Community

Cover image for Building a Double Pendulum Chaos Simulator in Prolog
Abolfazl Mohammadijoo
Abolfazl Mohammadijoo

Posted on

Building a Double Pendulum Chaos Simulator in Prolog

Most developers know Prolog as a language for symbolic reasoning, expert systems, search, theorem proving, and artificial intelligence. But can Prolog also be used to build a numerical physics simulator with a desktop GUI?

That was the motivation behind my project:

Prolog Double Pendulum Chaos Simulator

Repository:

https://github.com/mohammadijoo/Prolog-Double-Pendulum-Chaos-Simulator

The project is a desktop GUI application written in SWI-Prolog using the XPCE graphical toolkit. It simulates the classical double pendulum, one of the most famous examples of deterministic chaos.

The application lets the user define physical parameters such as initial angles, angular velocities, link lengths, masses, gravity, damping, numerical time step, and perturbation size. Then it animates the double pendulum and draws the trajectory of the outer endpoint.

The interesting part is that the motion is completely deterministic, but for many initial conditions it becomes visually irregular, highly sensitive, and practically unpredictable.

That is the essence of chaos.


What is a double pendulum?

A simple pendulum has one mass attached to one link. For small angles, it behaves almost like a linear oscillator. Its motion is smooth, periodic, and relatively easy to predict.

A double pendulum adds only one more link and one more mass:

  • Link 1 rotates around a fixed pivot.
  • Link 2 rotates around the end of link 1.
  • Each link has its own angle and angular velocity.
  • Gravity acts on both masses.

That small structural change is enough to make the dynamics much richer.

The state of the system can be written as:

x=[θ1,θ2,ω1,ω2]T x = [\theta_1,\theta_2,\omega_1,\omega_2]^T

where:

Symbol Meaning
theta1 / θ1\theta_1 angle of the first link
theta2 / θ2\theta_2 angle of the second link
omega1 / ω1\omega_1 angular velocity of the first link
omega2 / ω2\omega_2 angular velocity of the second link

In first-order state-space form:

θ˙1=ω1 \dot{\theta}_1 = \omega_1
θ˙2=ω2 \dot{\theta}_2 = \omega_2
ω˙1=f1(θ1,θ2,ω1,ω2,m1,m2,L1,L2,g) \dot{\omega}_1 = f_1(\theta_1,\theta_2,\omega_1,\omega_2,m_1,m_2,L_1,L_2,g)
ω˙2=f2(θ1,θ2,ω1,ω2,m1,m2,L1,L2,g) \dot{\omega}_2 = f_2(\theta_1,\theta_2,\omega_1,\omega_2,m_1,m_2,L_1,L_2,g)

This means the angular accelerations depend on the current angles, angular velocities, masses, lengths, and gravity.


Why is the double pendulum chaotic?

Chaos does not mean randomness.

A chaotic system can be fully deterministic. The equations are fixed. There is no random force inside the mathematical model. But tiny differences in the starting condition can grow rapidly and produce very different future behavior.

This is called sensitive dependence on initial conditions, often described as the butterfly effect.

In this project, I added a small perturbation option so that the user can compare two nearly identical initial states:

xA(0)=[θ1,θ2,ω1,ω2]T x_A(0) = [\theta_1,\theta_2,\omega_1,\omega_2]^T
xB(0)=[θ1+δ,θ2,ω1,ω2]T x_B(0) = [\theta_1+\delta,\theta_2,\omega_1,\omega_2]^T

Here, δ\delta may be extremely small, for example:

δ=0.05 \delta = 0.05^\circ

At the beginning, both motions may look almost identical. After some time, the trajectories can separate dramatically.

That is not because the simulator is broken. It is exactly what the nonlinear dynamics predict.

The double pendulum becomes chaotic because of several factors.

1. Nonlinear trigonometric coupling

The equations contain terms like:

sin(θ1θ2) \sin(\theta_1-\theta_2)
cos(θ1θ2) \cos(\theta_1-\theta_2)
sin(θ12θ2) \sin(\theta_1-2\theta_2)

These terms couple the two links in a nonlinear way.

2. Velocity-squared terms

The accelerations contain terms involving:

ω12,ω22 \omega_1^2,\quad \omega_2^2

These terms represent inertial and centripetal effects. When the pendulum moves fast, these nonlinear terms become very important.

3. Energy transfer between links

Energy can move back and forth between the two links. Sometimes the second link swings gently. Sometimes it flips rapidly. This exchange creates complex motion.

4. Bounded but irregular motion

The pendulum is physically bounded by its link lengths, but the endpoint path can become tangled and aperiodic. This is a typical sign of deterministic chaos: the motion is bounded, but it does not settle into a simple repeating pattern.


The implemented dynamic model

For angles measured from the downward vertical direction, the project uses the classical double-pendulum equations.

Define:

Δ=θ1θ2 \Delta = \theta_1-\theta_2
D=2m1+m2m2cos(2θ12θ2) D = 2m_1 + m_2 - m_2\cos(2\theta_1-2\theta_2)

Then the angular acceleration of the first link is:

ω˙1=g(2m1+m2)sin(θ1)m2gsin(θ12θ2)2m2sin(Δ)(ω22L2+ω12L1cos(Δ))L1Dcω1 \dot{\omega}_1 = \frac{ -g(2m_1+m_2)\sin(\theta_1) -m_2g\sin(\theta_1-2\theta_2) -2m_2\sin(\Delta)(\omega_2^2L_2+\omega_1^2L_1\cos(\Delta)) } {L_1D} -c\omega_1

The angular acceleration of the second link is:

ω˙2=2sin(Δ)(ω12L1(m1+m2)+g(m1+m2)cos(θ1)+ω22L2m2cos(Δ))L2Dcω2 \dot{\omega}_2 = \frac{ 2\sin(\Delta) \left( \omega_1^2L_1(m_1+m_2) +g(m_1+m_2)\cos(\theta_1) +\omega_2^2L_2m_2\cos(\Delta) \right) } {L_2D} -c\omega_2

where:

Symbol Meaning
m1,m2m_1,m_2 masses
L1,L2L_1,L_2 link lengths
gg gravitational acceleration
cc optional damping coefficient

When c=0c=0 , the system is ideal and conservative except for numerical integration error.

When c>0c>0 , a small damping term is applied.


Converting angles to Cartesian positions

To draw the pendulum, the simulator converts angular states into Cartesian coordinates.

The first bob position is:

x1=L1sin(θ1) x_1 = L_1\sin(\theta_1)
y1=L1cos(θ1) y_1 = L_1\cos(\theta_1)

The second bob position is:

x2=x1+L2sin(θ2) x_2 = x_1 + L_2\sin(\theta_2)
y2=y1+L2cos(θ2) y_2 = y_1 + L_2\cos(\theta_2)

The simulator draws the trajectory of:

(x2,y2) (x_2,y_2)

which is the endpoint of the outer link.

That endpoint trajectory is the most visually interesting part of the simulation. It often forms irregular loops, folds, and tangled paths.


Numerical integration with RK4

The system is described by nonlinear differential equations. To animate it, the simulator must repeatedly advance the state forward in time.

For this project I used the classical fourth-order Runge-Kutta method, usually called RK4.

For a state equation:

x˙=f(x,t) \dot{x} = f(x,t)

RK4 computes:

k1=f(xn,tn) k_1 = f(x_n,t_n)
k2=f(xn+h2k1,tn+h2) k_2 = f\left(x_n+\frac{h}{2}k_1,t_n+\frac{h}{2}\right)
k3=f(xn+h2k2,tn+h2) k_3 = f\left(x_n+\frac{h}{2}k_2,t_n+\frac{h}{2}\right)
k4=f(xn+hk3,tn+h) k_4 = f(x_n+hk_3,t_n+h)

and then:

xn+1=xn+h6(k1+2k2+2k3+k4) x_{n+1} = x_n + \frac{h}{6}(k_1+2k_2+2k_3+k_4)

In the GUI, the user can choose the time step dt.

A smaller value such as 0.01 usually gives smoother and more accurate behavior.

A larger value such as 0.03 or 0.04 may run faster but can introduce larger numerical error.

This is especially important in chaotic systems, because numerical error can also grow over time.


Why use Prolog for this?

Prolog is usually not the first language people choose for physics simulation. Python, MATLAB, C++, Julia, or JavaScript are more common choices.

That is exactly why this project was interesting.

Prolog is a logic programming language. Instead of writing programs mainly as sequences of commands, you describe facts, rules, relations, and goals.

A Prolog predicate can describe a relationship such as:

deg_to_rad(Degrees, Radians).
Enter fullscreen mode Exit fullscreen mode

or:

rk4_step(State, Params, Dt, NextState).
Enter fullscreen mode Exit fullscreen mode

In this project, Prolog is used for:

  • simulation state management
  • parsing user input
  • numerical derivative computation
  • RK4 integration
  • GUI control logic
  • drawing commands
  • event handling
  • timer-based animation
  • logging and reset behavior

This makes the project a useful experiment in applying a symbolic/logical language to a numerical and graphical problem.

The main lesson is that Prolog is not limited to toy examples or pure symbolic AI. With SWI-Prolog and XPCE, it can also build interactive desktop applications.


SWI-Prolog and XPCE

The project uses SWI-Prolog, a mature open-source Prolog implementation.

For the GUI, it uses XPCE, the graphical toolkit available with SWI-Prolog.

XPCE provides GUI elements such as:

  • frames
  • dialogs
  • buttons
  • text fields
  • drawing canvases
  • graphical objects
  • timers
  • event messages

The simulator uses XPCE to create:

  • the main desktop application window
  • a MATLAB-like trajectory view
  • a CAD-like mechanism view
  • control fields for initial conditions
  • Play / Pause and Reset buttons
  • real-time drawing of links, bobs, pivots, grids, and trajectories

GUI concept

The GUI is divided into two main visual areas.

Left pane: trajectory view

The left side shows the endpoint trajectory. It is similar to a scientific plotting or MATLAB-style visualization.

It includes:

  • coordinate grid
  • axes
  • double pendulum shape
  • endpoint trail
  • energy drift information

This view emphasizes the mathematical behavior of the system.

Right pane: mechanism view

The right side shows the physical pendulum in a more mechanical or CAD-like style.

It includes:

  • pivot
  • first link
  • second link
  • first bob
  • second bob
  • current mechanism configuration

This view emphasizes the physical structure of the system.

Bottom control pane

The bottom pane contains the input fields and controls:

  • initial angle 1
  • initial angle 2
  • angular velocity 1
  • angular velocity 2
  • link lengths
  • masses
  • gravity
  • damping
  • perturbation
  • time step
  • maximum trail points
  • Play / Pause
  • Reset
  • clock
  • motion log

Repository structure

The repository is organized as follows:

prolog-double-pendulum-chaos-simulator/
│
├── run.pl
├── README.md
├── LICENSE
├── .gitignore
├── CONTRIBUTING.md
│
├── src/
│   ├── double_pendulum_gui.pl
│   └── double_pendulum_physics.pl
│
├── docs/
│   ├── EQUATIONS.md
│   └── DEVELOPMENT_NOTES.md
│
├── examples/
│   └── initial_conditions.txt
│
└── screenshots/
    └── .gitkeep
Enter fullscreen mode Exit fullscreen mode

The two most important source files are:

src/double_pendulum_physics.pl
src/double_pendulum_gui.pl
Enter fullscreen mode Exit fullscreen mode

Physics module

The physics module contains the mathematical model and numerical integration code.

Important predicates include:

deg_to_rad(+Degrees, -Radians)
Enter fullscreen mode Exit fullscreen mode

Converts degrees to radians.

rad_to_deg(+Radians, -Degrees)
Enter fullscreen mode Exit fullscreen mode

Converts radians to degrees.

derivatives(+State, +Params, -Derivative)
Enter fullscreen mode Exit fullscreen mode

Computes the state derivative of the double pendulum.

Example state representation:

state(Theta1, Theta2, Omega1, Omega2)
Enter fullscreen mode Exit fullscreen mode

Example parameter representation:

params(M1, M2, L1, L2, G, Damping)
Enter fullscreen mode Exit fullscreen mode

Derivative representation:

deriv(DTheta1, DTheta2, DOmega1, DOmega2)
Enter fullscreen mode Exit fullscreen mode

The RK4 integrator is exposed through:

rk4_step(+State, +Params, +Dt, -NextState)
Enter fullscreen mode Exit fullscreen mode

The Cartesian position calculation is handled by:

bob_positions(+State, +Params, -X1, -Y1, -X2, -Y2)
Enter fullscreen mode Exit fullscreen mode

The module also estimates total mechanical energy:

total_energy(+State, +Params, -Energy)
Enter fullscreen mode Exit fullscreen mode

This helps observe numerical drift during simulation.


GUI module

The GUI module contains the XPCE interface and animation loop.

Important predicates include:

main.
Enter fullscreen mode Exit fullscreen mode

which builds and opens the desktop GUI.

build_gui.
Enter fullscreen mode Exit fullscreen mode

which creates the main frame, drawing canvas, text fields, buttons, labels, and layout.

toggle_simulation.
Enter fullscreen mode Exit fullscreen mode

which handles Play / Pause behavior.

start_new_simulation.
Enter fullscreen mode Exit fullscreen mode

which reads the input fields, builds the initial state, creates the perturbation state, creates the timer, and starts the animation.

simulation_tick.
Enter fullscreen mode Exit fullscreen mode

which is called repeatedly by the XPCE timer.

Each tick performs the main animation tasks:

  • advance both pendulums using RK4
  • update the simulation clock
  • append new endpoint trajectory points
  • redraw the GUI
  • update logs
  • stop automatically after the maximum simulation time

The drawing helper predicates wrap XPCE drawing objects such as lines, circles, boxes, and text.


How to run the project

First install SWI-Prolog with XPCE support.

Clone the repository:

git clone https://github.com/mohammadijoo/Prolog-Double-Pendulum-Chaos-Simulator.git
cd Prolog-Double-Pendulum-Chaos-Simulator
Enter fullscreen mode Exit fullscreen mode

Run:

swipl -q -f none run.pl
Enter fullscreen mode Exit fullscreen mode

You can also start SWI-Prolog manually:

swipl
Enter fullscreen mode Exit fullscreen mode

Then load and run:

?- [run].
?- main.
Enter fullscreen mode Exit fullscreen mode

To verify that XPCE is available:

?- use_module(library(pce)).
true.
Enter fullscreen mode Exit fullscreen mode

Suggested initial conditions

Here are some useful test cases.

Strong chaotic behavior

theta1 deg      120
theta2 deg      -10
omega1 rad/s    0.0
omega2 rad/s    0.0
L1 m            1.0
L2 m            1.0
m1 kg           1.0
m2 kg           1.0
g m/s^2         9.81
damping         0.000
perturb deg     0.05
dt s            0.02
trail points    1500
Enter fullscreen mode Exit fullscreen mode

Smaller perturbation

theta1 deg      120
theta2 deg      -10
omega1 rad/s    0.0
omega2 rad/s    0.0
perturb deg     0.005
dt s            0.01
Enter fullscreen mode Exit fullscreen mode

High-energy motion

theta1 deg      170
theta2 deg      80
omega1 rad/s    0.0
omega2 rad/s    0.0
perturb deg     0.05
dt s            0.01
Enter fullscreen mode Exit fullscreen mode

Damped motion

theta1 deg      130
theta2 deg      -30
omega1 rad/s    0.0
omega2 rad/s    0.0
damping         0.02
perturb deg     0.05
dt s            0.02
Enter fullscreen mode Exit fullscreen mode

With damping, the system eventually loses energy, but the early transient motion can still show strong sensitivity.


What this project demonstrates

This project is not just a pendulum animation.

It demonstrates several important ideas:

  1. Deterministic chaos
    The system follows exact equations, but long-term prediction becomes practically difficult.

  2. Sensitivity to initial conditions
    Very small perturbations can eventually produce very different trajectories.

  3. Nonlinear dynamics
    Trigonometric coupling and velocity-squared terms make the system behave very differently from a linear oscillator.

  4. Numerical simulation
    RK4 integration makes it possible to animate the differential equations step by step.

  5. Prolog beyond symbolic AI
    Prolog can also be used for GUI applications, numerical computation, and engineering-style educational software.

  6. Visualization as a learning tool
    Seeing the endpoint trajectory makes the concept of chaos much easier to understand than formulas alone.


Screenshots


Related videos

My simulation video:

Other useful double-pendulum chaos visual references:


Possible future improvements

Some possible directions for future versions:

  • export trajectory data to CSV
  • add phase-space plots
  • add Lyapunov exponent estimation
  • compare Euler, RK2, RK4, and symplectic integration
  • add real-time parameter sliders
  • add multi-pendulum ensemble visualization
  • add GIF/video export
  • add web version using Prolog backend and JavaScript frontend
  • add unit tests for the physics predicates
  • improve energy conservation diagnostics

A particularly interesting next step would be estimating the largest Lyapunov exponent. That would turn the visual idea of “nearby states separating” into a measurable quantity.

Conceptually, if two nearby trajectories separate approximately as:

d(t)d(0)eλt d(t) \approx d(0)e^{\lambda t}

then λ\lambda is a Lyapunov exponent.

If:

λ>0 \lambda > 0

the system shows exponential divergence of nearby trajectories, which is a signature of chaos.


Conclusion

The double pendulum is a beautiful example of how simple mechanical components can produce complex nonlinear behavior.

Two links, two masses, gravity, and deterministic equations are enough to create motion that appears almost random.

Using Prolog for this project made it even more interesting. It shows that Prolog can be used not only for symbolic reasoning and AI-style logic programming, but also for building interactive engineering simulations with a desktop GUI.

Repository:

https://github.com/mohammadijoo/Prolog-Double-Pendulum-Chaos-Simulator

If you are interested in Prolog, numerical simulation, nonlinear dynamics, or educational engineering software, feel free to check the repository, try the simulator, and suggest improvements.

Thanks for reading.

Top comments (0)