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:
where:
| Symbol | Meaning |
|---|---|
theta1 /
|
angle of the first link |
theta2 /
|
angle of the second link |
omega1 /
|
angular velocity of the first link |
omega2 /
|
angular velocity of the second link |
In first-order state-space form:
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:
Here, may be extremely small, for example:
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:
These terms couple the two links in a nonlinear way.
2. Velocity-squared terms
The accelerations contain terms involving:
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:
Then the angular acceleration of the first link is:
The angular acceleration of the second link is:
where:
| Symbol | Meaning |
|---|---|
| masses | |
| link lengths | |
| gravitational acceleration | |
| optional damping coefficient |
When , the system is ideal and conservative except for numerical integration error.
When , 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:
The second bob position is:
The simulator draws the trajectory of:
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:
RK4 computes:
and then:
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).
or:
rk4_step(State, Params, Dt, NextState).
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
The two most important source files are:
src/double_pendulum_physics.pl
src/double_pendulum_gui.pl
Physics module
The physics module contains the mathematical model and numerical integration code.
Important predicates include:
deg_to_rad(+Degrees, -Radians)
Converts degrees to radians.
rad_to_deg(+Radians, -Degrees)
Converts radians to degrees.
derivatives(+State, +Params, -Derivative)
Computes the state derivative of the double pendulum.
Example state representation:
state(Theta1, Theta2, Omega1, Omega2)
Example parameter representation:
params(M1, M2, L1, L2, G, Damping)
Derivative representation:
deriv(DTheta1, DTheta2, DOmega1, DOmega2)
The RK4 integrator is exposed through:
rk4_step(+State, +Params, +Dt, -NextState)
The Cartesian position calculation is handled by:
bob_positions(+State, +Params, -X1, -Y1, -X2, -Y2)
The module also estimates total mechanical energy:
total_energy(+State, +Params, -Energy)
This helps observe numerical drift during simulation.
GUI module
The GUI module contains the XPCE interface and animation loop.
Important predicates include:
main.
which builds and opens the desktop GUI.
build_gui.
which creates the main frame, drawing canvas, text fields, buttons, labels, and layout.
toggle_simulation.
which handles Play / Pause behavior.
start_new_simulation.
which reads the input fields, builds the initial state, creates the perturbation state, creates the timer, and starts the animation.
simulation_tick.
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
Run:
swipl -q -f none run.pl
You can also start SWI-Prolog manually:
swipl
Then load and run:
?- [run].
?- main.
To verify that XPCE is available:
?- use_module(library(pce)).
true.
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
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
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
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
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:
Deterministic chaos
The system follows exact equations, but long-term prediction becomes practically difficult.Sensitivity to initial conditions
Very small perturbations can eventually produce very different trajectories.Nonlinear dynamics
Trigonometric coupling and velocity-squared terms make the system behave very differently from a linear oscillator.Numerical simulation
RK4 integration makes it possible to animate the differential equations step by step.Prolog beyond symbolic AI
Prolog can also be used for GUI applications, numerical computation, and engineering-style educational software.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:
then is a Lyapunov exponent.
If:
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)