N-Body Gravitational Simulation

Multi-Language Performance Comparison: JAX (GPU) ยท Fortran ยท C ยท C++ ยท Python

Adam Field | Computational Physics ISP | Worcester Polytechnic Institute

Project Overview

๐ŸŽฏ Objective

Implement the same gravitational N-body simulation in five different languages and compare their performance characteristics on CPU and GPU architectures.

๐Ÿ”ฌ Physics

Simulates gravitational interactions between N particles using the Velocity Verlet integrator, which conserves energy to within 0.01% over 1000 timesteps.

๐Ÿ’ป Implementations

  • JAX (GPU) GPU-accelerated with JIT compilation
  • Fortran OpenMP parallelized on CPU
  • C++ Modern C++ with pybind11
  • C Pure C with ctypes wrapper
  • Python NumPy baseline

๐Ÿ“Š Key Finding

At N=1000 particles: JAX (GPU) is 1384ร— faster than Python and 17ร— faster than Fortran!

-
Max Particles Tested
-
Timesteps per Benchmark
-
Energy Conservation
-
GPU Speedup (N=1000)

Performance Analysis

Scaling: Time per Step vs N

Speedup vs Python Baseline

๐Ÿ“‹ Detailed Performance Results

Implementation N=10 N=50 N=100 N=500 N=1000

All times in milliseconds per timestep

โšก Energy Conservation Quality

All implementations conserve energy to < 0.01% for N=50 over 1000 steps, validating the Velocity Verlet integrator.

Trajectory Visualizations

2D Trajectory Animation

2D N-body trajectory animation

Particle trajectories in the XY plane showing gravitational interactions

Energy Conservation

Energy conservation plot

Kinetic, potential, and total energy evolution over time

Scaling Analysis

Comprehensive scaling analysis

Performance scaling showing O(Nยฒ) complexity

GPU Crossover Analysis

GPU crossover analysis

GPU becomes faster than CPU at N โ‰ˆ 75-100 particles

Interactive 3D Visualization

โš ๏ธ Note: This is a simple browser-based visualization. For high-performance simulations with N > 1000, use the Python/JAX implementation on GPU.

About This Project

๐ŸŽ“ Academic Context

Course: Computational Physics Independent Study (ISP)

Institution: Worcester Polytechnic Institute

Student: Adam Field

Date: January 2026

๐Ÿ› ๏ธ Technologies Used

  • JAX: GPU acceleration with JIT compilation
  • Fortran: f2py wrapper with OpenMP
  • C++: pybind11 for Python bindings
  • C: ctypes wrapper
  • Python: NumPy, Matplotlib, SciPy
  • Web: Three.js, Chart.js, vanilla JavaScript

๐Ÿ“š Key Learning Outcomes

  • Numerical integration methods (Velocity Verlet)
  • GPU programming and parallelization
  • Language interoperability (Python โ†” C/C++/Fortran)
  • Performance benchmarking and profiling
  • Scientific visualization
  • Computational complexity analysis

๐Ÿ”— Resources

Repository: computational_physics_isp/nbody_comparison/

Documentation: See docs/theory.md and docs/results.md

Test Suite: tests/test_accuracy.py

Contact: adfield@wpi.edu