🌌 3-Body Gravitational Simulation
A Python-based 3D visualization of the three-body problem using matplotlib, scipy, and numpy. This project is a physics-inspired simulation that visually demonstrates the chaotic dynamics of three mutually gravitating bodies in space.
🎯 Focus: Educational simulation with real-time animation and configurable parameters.
✨ Features
- 🔧 Interactive CLI config menu (customize masses, positions, velocities,
G, and more) - 🎥 Smooth 3D animation using
matplotlib.animation - 📦 Saves simulation data as CSV (
3body_simulation_output.csv) - 🎬 Exports animation as MP4 using FFmpeg
- 🧠 Stop condition when all bodies leave the viewport
- 🚫 Hides out-of-bound bodies gracefully to avoid clutter
- 📈 Easy to analyze trajectory data post-simulation
📦 Requirements
- Python 3.7+
numpyscipymatplotlibpandasffmpeg(for saving MP4)
Install dependencies:
pip install numpy scipy matplotlib pandas
Install FFmpeg (for saving animation):
- Windows: Download from ffmpeg.org and add it to PATH
- Linux/macOS:
sudo apt install ffmpeg # Debian/Ubuntu
brew install ffmpeg # macOS (Homebrew)
🚀 Run the Simulation
python 3body_simulation.py
You'll see a CLI menu:
- Press Enter to use defaults
- Type E to edit custom values like mass, velocity, position,
G, etc.
After the simulation:
- You’ll get an MP4 animation
- All positional data will be saved to a CSV for further analysis
📊 Optional Data Plotting (Post-Simulation)
To analyze saved trajectories:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("3body_simulation_output.csv")
for planet_id in [1, 2, 3]:
subset = df[df['planet'] == planet_id]
plt.plot(subset['x'], subset['y'], label=f'Body {planet_id}')
plt.xlabel('X')
plt.ylabel('Y')
plt.title("2D Trajectory Plot (XY Plane)")
plt.legend()
plt.grid(True)
plt.show()
⚠️ Known Limitations and Inaccuracies
This simulator prioritizes visual understanding and usability over exact scientific accuracy.
🔬 Physics & Math Simplifications:
- No collisions: Bodies are point masses with no radius or collision detection
- No energy tracking: System energy is not computed or conserved
- Simplified gravity: A small constant (
+1e-5) is added in the denominator to avoid division by zero - No adaptive time step: Fixed time sampling via
np.linspaceis used - Newtonian only: No general relativity, relativistic corrections, or external forces
🎥 Rendering/Animation:
- Bodies are still rendered briefly after leaving axis limits for smoother transition
- Simulation stops only after all 3 bodies exit bounds, not individually
🛠️ To-Do / Future Enhancements
- Add energy and angular momentum conservation metrics
- Enable real-world unit support (e.g., AU, kg, seconds)
- Collision detection or merging logic
- Symplectic integrators (Leapfrog/Euler-Cromer) for better long-term stability
- Web-based interface using WebGL (maybe Three.js)
📁 Project Structure
.
├── 3body_simulation.py # Main simulation code
├── data.py
├── 3body_simulation_output.csv # Trajectory data (auto-generated)
├── media/
│ └── 3body_simulation.mp4 # Output animation (auto-generated)
└── README.md # This file
💡 Inspiration
The chaotic nature of the 3-body problem is a beautiful representation of how simple rules can lead to complex behavior. This simulation is my take on exploring it visually, interactively, and accessibly.
🤝 License
This project is free to use under the MIT License. Feel free to fork, improve, or contribute back!
🙌 Acknowledgments
scipy.integrate.solve_ivp— for solving the ODE systemmatplotlib.animation— for powerful visual rendering- Community contributors and educators for inspiring open-source learning
Metadata
Release files for threebodysim 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| threebodysim-0.1.0.tar.gz | 6.7 kB | Without provenance | Details for threebodysim-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| threebodysim-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for threebodysim-0.1.0-py3-none-any.whl |
Total release size: 14.0 kB
Release files / threebodysim-0.1.0.tar.gz
| Download URL | threebodysim-0.1.0.tar.gz |
|---|---|
| Size | 6.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
be4f8e3d8e3784ccff6d7ccaa1502b67285e64b365aeff5f234d93bd19ac0853
|
|
BLAKE2b-256 checksum How to use checksums |
333a859474afe96ba9821b9b0bd2155e3ad03f3236876b1755a414b978c9c576
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.13
|
Release files / threebodysim-0.1.0-py3-none-any.whl
| Download URL | threebodysim-0.1.0-py3-none-any.whl |
|---|---|
| Size | 7.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
09016346070a8fcff6807c841afb2820a2c10b075408813018562bef8170416c
|
|
BLAKE2b-256 checksum How to use checksums |
90939be5d4a778df1f968573c28b0e62e1210517976a3f8e3add035c57c2961b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.13
|
Security for threebodysim 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.