A desktop GUI application written in SWI-Prolog using the XPCE graphical toolkit to demonstrate chaotic dynamics through the classical double pendulum.
The simulator renders a white double pendulum on a dark background and draws the trajectory of the outer endpoint. The motion is deterministic, but for many initial conditions it becomes irregular and highly sensitive to small changes in the starting angles or angular velocities. This is the visual demonstration of the butterfly effect, also called sensitive dependence on initial conditions.
- Project overview
- Technologies used
- GUI layout
- Chaos theory background
- Real-world chaotic phenomena
- Double pendulum dynamics
- Why the double pendulum is chaotic
- Numerical integration method
- Repository structure
- Code architecture
- Install SWI-Prolog and XPCE
- Verify the installation
- Run the project
- Suggested initial conditions
- Troubleshooting
- Simulation video
- References
- License
The Prolog Double Pendulum Chaos Simulator is an educational and engineering-style simulator for visualizing nonlinear motion, instability, and chaotic divergence in a double pendulum.
The user enters initial conditions such as:
- Initial angle of the first link,
$\theta_1$ - Initial angle of the second link,
$\theta_2$ - Initial angular velocity of the first link,
$\omega_1$ - Initial angular velocity of the second link,
$\omega_2$ - Link lengths,
$L_1$ and$L_2$ - Masses,
$m_1$ and$m_2$ - Gravity,
$g$ - Optional damping
- Small angular perturbation that can be used to test sensitivity to initial conditions
- Numerical time step
$\Delta t$ - Maximum number of trajectory points shown
After pressing Play / Pause, the GUI animates the double pendulum and draws the path of the outer endpoint. The trajectory is not a simple sinusoid or closed harmonic curve. For many initial conditions, the path becomes irregular, tangled, and strongly dependent on the starting configuration.
The simulator automatically stops after 10 minutes of simulated time and returns to the waiting state.
SWI-Prolog is a mature, open-source Prolog implementation widely used in education, research, symbolic computation, logic programming, and knowledge-based applications.
This project uses SWI-Prolog for:
- GUI control logic
- Simulation state management
- Numerical integration
- Drawing commands
- Event handling
- User input parsing
- Runtime logging
XPCE is the native GUI toolkit available with SWI-Prolog. It provides windows, dialogs, buttons, text fields, graphical canvases, shapes, timers, and event messages.
This project uses XPCE for:
- The desktop application window
- The top animation canvas
- The bottom control pane
- Text input boxes
- Play / Pause and Reset buttons
- Real-time drawing of links, bobs, pivots, grid lines, and trajectories
- Timer-based animation
The application follows the requested layout concept:
+---------------------------------------------------------------+
| |
| Top pane: 85% of app height |
| |
| +-----------------------------+-----------------------------+|
| | Left pane: 50% width | Right pane: 50% width ||
| | MATLAB-like view | CAD-like view ||
| | trajectory of outer bob | mechanical double pendulum ||
| | grid + axes + path | pivots + links + bobs ||
| +-----------------------------+-----------------------------+|
| |
+---------------------------------------------------------------+
| Bottom pane: 15% of app height |
| Initial conditions | equation | Play/Pause | clock | log |
+---------------------------------------------------------------+
The left pane shows:
- A coordinate grid
- Horizontal and vertical axes
- The current double pendulum shape
- The outer endpoint trajectory
- Energy drift information
This view is intended to resemble the type of phase/trajectory visualization commonly used in MATLAB, scientific plotting, and control-system simulation.
The right pane shows:
- A mechanical drawing style double pendulum
- Pivot support
- Link 1 and link 2
- Bob masses
$m_1$ and$m_2$ - White links, pivots, bobs, and motion/status logs
This view is intended to look more like a mechanism/CAD sketch, emphasizing the physical links and joints.
The bottom pane contains:
- Text fields for initial conditions and parameters
- Play / Pause button
- Reset button
- Main dynamic model summary
- Clock counter
- Motion log
The clock counts up to 600 seconds, corresponding to 10 minutes of simulation time.
Chaos theory studies deterministic systems whose long-term behavior is highly sensitive to initial conditions. A chaotic system is not random in the sense of being governed by probability at every instant. Instead, it follows deterministic laws, but small differences in the starting state can grow rapidly and produce very different future trajectories.
A chaotic system usually has these properties:
-
Determinism
The system follows definite equations of motion. If the exact state and equations were known with infinite precision, the future state would be determined. -
Nonlinearity
The equations contain nonlinear couplings such as products, trigonometric functions, squared velocities, or feedback terms. Nonlinearity allows energy transfer between modes and can amplify differences. -
Sensitive dependence on initial conditions
Two states that begin very close together can separate quickly. This is the butterfly effect. -
Aperiodic long-term behavior
The motion may not settle into a simple repeating orbit. It can remain bounded but irregular. -
Phase-space stretching and folding
Chaotic flows often stretch nearby states apart while folding trajectories back into a bounded region. This mechanism creates complex attractors or complicated reachable sets.
The phrase butterfly effect is commonly associated with Edward Lorenz's work on weather prediction. It describes how a very small perturbation, such as a tiny change in a starting variable, can lead to a large difference later.
In this simulator, the butterfly effect is demonstrated by changing the initial state only slightly and observing how the white double pendulum trajectory changes over time. For example, compare two runs that differ only by a tiny change in the first initial angle:
where
Chaos appears in many real-world systems. The important point is that chaos does not mean the system has no rules. It means that deterministic rules can produce practically unpredictable motion.
Weather is one of the most famous chaotic systems. Atmospheric motion is governed by fluid dynamics, thermodynamics, pressure gradients, rotation of Earth, moisture, and radiative transfer. Even with powerful computers, small uncertainty in the initial state limits long-term forecast accuracy.
Ocean circulation involves nonlinear fluid motion, density gradients, salinity, temperature, and wind forcing. Vortices and turbulent mixing can create sensitive dependence on initial conditions.
Turbulence in fluids is a major example of nonlinear complex motion. Although the Navier-Stokes equations are deterministic, turbulent eddies interact across scales and produce irregular motion.
Some biological population models, such as the logistic map under certain parameter values, can show chaotic behavior. Small differences in population size or growth rate can lead to large long-term differences.
Nonlinear circuits, such as Chua's circuit, can show chaotic oscillations. These systems are useful for studying nonlinear dynamics experimentally.
Mechanical systems with impacts, friction, flexible links, backlash, underactuation, or strong nonlinear coupling can show complex behavior. The double pendulum is a clean educational example of this type of nonlinear mechanical behavior.
Multi-body gravitational systems can become chaotic. Long-term prediction of some orbital configurations is difficult because tiny perturbations can accumulate over time.
Heart rhythms, neural activity, and some biomechanical systems can exhibit nonlinear and chaotic-like behavior. This does not mean they are random; it means that nonlinear feedback and coupling can create complex dynamics.
A double pendulum consists of two pendulum links connected in series:
- Link 1 rotates about a fixed pivot.
- Link 2 rotates about the end of link 1.
- Each link has a mass/bob.
- Gravity acts downward.
The state variables are:
| Symbol | Meaning |
|---|---|
| angle of link 1 from the downward vertical | |
| angle of link 2 from the downward vertical | |
| angular velocity of link 1 | |
| angular velocity of link 2 |
The state vector is:
The first-order state-space form is:
For angles measured from the downward vertical direction, the implemented equations are:
where:
| Symbol | Meaning |
|---|---|
| masses | |
| link lengths | |
| gravitational acceleration | |
| optional damping coefficient |
When
The position of the first bob is:
The position of the second bob is:
The simulator draws the trajectory of
The simulator also estimates total mechanical energy to help diagnose numerical drift.
Kinetic energy:
Potential energy:
Total energy:
A small energy drift is normal in numerical simulation, especially for long runs or large time steps.
The double pendulum is chaotic because it is nonlinear, coupled, and capable of transferring energy between rotational modes.
The equations contain terms such as:
These terms make the acceleration of each link depend nonlinearly on both angles.
The angular accelerations contain terms such as:
These terms represent centripetal and inertial coupling. They strongly affect the motion when the pendulum rotates quickly.
Energy can move back and forth between link 1 and link 2. Sometimes link 2 swings gently; sometimes it flips over rapidly. This energy exchange can amplify small differences in angle or angular velocity.
If two runs start with:
but all other parameters are equal, the first few seconds may look similar. Later, the endpoint trajectory can become completely different. In the GUI, this sensitivity is observed by restarting the white-on-dark pendulum with slightly different initial conditions and comparing the resulting endpoint path.
The pendulum remains mechanically bounded by its link lengths, but the endpoint trajectory can become highly irregular. This is a typical signature of deterministic chaos: bounded motion without simple periodic repetition.
The simulator uses a classical fourth-order Runge-Kutta method, usually written as RK4.
For a state equation:
RK4 computes:
In this project, h is the user-defined dt s value. The default is:
dt = 0.02 seconds
For smoother and more accurate simulation, use smaller time steps such as 0.01. For faster but less accurate simulation, use larger time steps such as 0.03 or 0.04.
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 project entry point.
Responsibilities:
- Loads the physics source file.
- Loads the GUI source file.
- Starts the GUI through SWI-Prolog initialization.
Main usage:
swipl -q -f none run.plContains the mathematical and numerical model.
Important predicates:
Converts degrees to radians.
deg_to_rad(+Degrees, -Radians)Converts radians to degrees.
rad_to_deg(+Radians, -Degrees)Computes the double pendulum state derivative.
derivatives(+State, +Params, -Derivative)Input state:
state(Theta1, Theta2, Omega1, Omega2)Input parameters:
params(M1, M2, L1, L2, G, Damping)Output derivative:
deriv(DTheta1, DTheta2, DOmega1, DOmega2)Advances the system by one time step using RK4.
rk4_step(+State, +Params, +Dt, -NextState)Computes the Cartesian positions of the two bobs.
bob_positions(+State, +Params, -X1, -Y1, -X2, -Y2)Computes total mechanical energy.
total_energy(+State, +Params, -Energy)Computes the physical distance between the outer endpoints of the primary and perturbed pendulums.
endpoint_separation(+StateA, +StateB, +Params, -Distance)Computes a state-space separation value between two double-pendulum states.
angular_separation(+StateA, +StateB, -Distance)Contains the XPCE GUI and animation loop.
Important predicates:
Builds and opens the desktop GUI.
main.Creates:
- Main frame
- Top drawing canvas
- Bottom control dialog
- Text input fields
- Play / Pause button
- Reset button
- Clock label
- Formula label
- Log label
Handles Play / Pause behavior:
- Starts a new simulation if no simulation exists.
- Pauses the timer if the simulation is running.
- Restarts the timer if the simulation is paused.
Reads the input fields, creates primary and perturbed states, creates the XPCE timer, and starts the animation loop.
Called repeatedly by the XPCE timer.
Responsibilities:
- Advance both pendulums using RK4.
- Update the simulation clock.
- Append endpoint trajectory points.
- Redraw both top panes.
- Update logs.
- Stop automatically at 600 seconds.
Stops the timer, clears simulation state, resets the clock, and returns the GUI to the waiting state.
The GUI file includes drawing helpers such as:
draw_line/7
draw_circle/7
draw_text/7
draw_grid/5
draw_pendulum/9
draw_trail/3These wrap XPCE drawing objects such as line, circle, box, and text.
This project requires SWI-Prolog with XPCE GUI support.
- Open the official SWI-Prolog stable download page:
https://www.swi-prolog.org/download/stable - Download the Windows 64-bit installer.
- Run the installer.
- During installation, enable adding SWI-Prolog to the system
PATHif the installer offers this option. - Open Command Prompt or PowerShell.
- Verify:
swipl --versionRecommended options:
- Open the official stable download page:
https://www.swi-prolog.org/download/stable - Download the macOS bundle.
- Install it like a normal macOS application.
- Ensure the
swiplcommand is available from Terminal.
brew update
brew install swi-prolog
swipl --versionIf swipl is not found after installing the macOS app bundle, use Homebrew or add the SWI-Prolog command-line tools path to your shell configuration.
Linux installation depends on the distribution.
sudo apt update
sudo apt install swi-prolog
swipl --versionFor newer builds, use the official SWI-Prolog PPA or Flatpak instructions from the SWI-Prolog download page.
sudo dnf install pl
swipl --versionIf the package name is not available as pl, search:
dnf search swi-prologsudo pacman -S swi-prolog
swipl --versionXPCE is required for this GUI project. On most full SWI-Prolog desktop installations, XPCE is included. On some minimal Linux packages, the GUI components may be packaged separately or may require additional X11/Wayland libraries.
swipl --versionExpected result:
SWI-Prolog version ...
swiplYou should see a prompt similar to:
?-At the Prolog prompt:
?- use_module(library(pce)).Expected result:
true.?- manpce.If a GUI documentation window opens, XPCE is working.
?- halt.Clone the repository or download the project files.
git clone https://github.com/YOUR_USERNAME/prolog-double-pendulum-chaos-simulator.git
cd prolog-double-pendulum-chaos-simulatorFrom PowerShell or Command Prompt:
swipl -q -f none run.plFrom Terminal:
swipl -q -f none run.plFrom a terminal:
swipl -q -f none run.plswiplThen:
?- [run].
?- main.Try the following values to produce visible 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
theta1 deg 120
theta2 deg -10
omega1 rad/s 0.0
omega2 rad/s 0.0
perturb deg 0.005
dt s 0.01
The first trajectory may look regular at first, but a slightly changed initial condition can produce a visibly different path later.
theta1 deg 170
theta2 deg 80
omega1 rad/s 0.0
omega2 rad/s 0.0
perturb deg 0.05
dt s 0.01
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.
Cause: SWI-Prolog is not in the system PATH.
Fix:
- Reinstall SWI-Prolog and enable the option to add it to
PATH, or - Add the SWI-Prolog
bindirectory manually to the Windows environment variables.
Typical path:
C:\Program Files\swipl\bin
Then restart PowerShell or Command Prompt.
Run:
which swiplIf no path appears, install SWI-Prolog again or fix your shell PATH.
Cause: XPCE is not installed or the installed SWI-Prolog package is minimal/headless.
Fix:
- Install the full SWI-Prolog distribution.
- On Linux, check whether your distribution has a separate GUI/XPCE package.
- Use the official SWI-Prolog stable installer/bundle if the distribution package is incomplete.
Cause: XPCE needs a graphical display. A headless server or WSL terminal may not have an available X11/Wayland display.
Fix options:
- Run the project on a desktop Linux session.
- Use WSLg on Windows 11.
- Install and configure an X server for older WSL setups.
- Check:
echo $DISPLAYIf DISPLAY is empty, GUI windows cannot open.
Possible causes:
- Too many trajectory points.
- Very small time step.
- Old hardware.
- Large application window.
Fix:
- Reduce
trail pointsfrom1500to500. - Increase
dt sfrom0.01to0.02or0.03. - Avoid resizing the window extremely large.
Possible causes:
- Time step is too large.
- Initial conditions are very high energy.
- The model is near fast rotations or flips.
Fix:
- Reduce
dt sto0.01or0.005. - Keep damping at
0.000for ideal dynamics, or use small damping such as0.005to reduce numerical blow-up. - Avoid extremely large angular velocities at the start.
Possible causes:
- The selected initial condition is close to regular or low-energy motion.
- The damping value is too high.
- The simulation time is too short to reveal sensitive dependence.
Fix:
- Try
theta1 deg = 120,theta2 deg = -10. - Set
damping = 0.000. - Try a second run with a slightly different value, such as
theta1 deg = 120.05, and compare the endpoint trajectory. - Run for a longer time.
Cause: The trajectory history is long.
Fix:
- Reduce
trail points. - Press
Resetand start again.
XPCE uses native drawing and fonts. Font rendering can differ between Windows, macOS, and Linux.
Fix:
- This does not affect the simulation.
- If desired, edit
draw_text/7insrc/double_pendulum_gui.pland replacehelveticawith another font available on your system.
Below is a link to the simulation video on YouTube.
The following videos show double-pendulum chaotic motion examples and can be useful as visual references:
- https://www.youtube.com/watch?v=pEjZd-AvPco
- https://www.youtube.com/watch?v=d0Z8wLLPNE0
- https://www.youtube.com/watch?v=U39RMUzCjiU
- https://www.youtube.com/watch?v=QXf95_EKS6E
- SWI-Prolog official website: https://www.swi-prolog.org/
- SWI-Prolog stable downloads: https://www.swi-prolog.org/download/stable
- XPCE official page: https://www.swi-prolog.org/packages/xpce/
- SWI-Prolog command-line options: https://www.swi-prolog.org/pldoc/man?section=cmdline
- SWI-Prolog project and IDE documentation: https://www.swi-prolog.org/man/IDE.html
- Classical mechanics textbooks on Lagrangian dynamics
- Nonlinear dynamics and chaos textbooks
- Numerical analysis references for Runge-Kutta integration
This project is released under the MIT License. See LICENSE.