# Physics Simulation Algorithms in TheAlgorithms/Python: N-Body Systems and Fluid Dynamics

> Explore N-body systems and fluid dynamics physics simulation algorithms in TheAlgorithms/Python. Learn how Euler integration and Reynolds numbers model physical phenomena.

- Repository: [The Algorithms/Python](https://github.com/TheAlgorithms/Python)
- Tags: deep-dive
- Published: 2026-02-24

---

**TheAlgorithms/Python repository implements physics simulation algorithms ranging from interactive N-body gravitational systems using Euler integration to analytical fluid dynamics calculations including terminal velocity and Reynolds number.**

The `physics` package in the [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python) repository demonstrates how fundamental physical phenomena can be modeled algorithmically in pure Python. These physics simulation algorithms span from time-stepped dynamical systems to closed-form analytical solutions, providing educational implementations of Newtonian mechanics, fluid dynamics, and wave propagation.

## Gravitational N-Body Simulation

The cornerstone of the physics package is an N-body gravitational simulator implemented in [`physics/n_body_simulation.py`](https://github.com/TheAlgorithms/Python/blob/main/physics/n_body_simulation.py). This algorithm models a system of point masses interacting through Newton’s universal gravitation, advancing the system state through explicit numerical integration.

### Data Structures and System Configuration

The simulation architecture centers on two primary classes. The `Body` class stores the state of individual masses, including position coordinates, velocity vectors, mass values, and rendering attributes. The `BodySystem` class aggregates multiple `Body` instances and maintains global simulation parameters including the gravitational constant `G`, a `time_factor` for scaling temporal evolution, and a `softening_factor` to handle numerical edge cases.

### Force Calculation with Gravitational Softening

For every ordered pair of bodies $(i, j)$ where $i \neq j$, the algorithm computes the gravitational force vector using Newton's law with a softening parameter $\epsilon$ to prevent division-by-zero singularities when $r \to 0$:

```python
dif_x = body2.position_x - body1.position_x
dif_y = body2.position_y - body1.position_y
distance = (dif_x**2 + dif_y**2 + softening_factor) ** 0.5
force_x += G * body2.mass * dif_x / distance**3
force_y += G * body2.mass * dif_y / distance**3

```

This implementation calculates the displacement vector $\mathbf{r}$ between bodies, applies the softening factor to the squared distance, and computes the force components proportional to $G \frac{m_1m_2}{r^3}\,\mathbf{r}$.

### Euler Integration Method

After summing forces from all interacting bodies, the system advances the simulation state using explicit Euler integration. First, each body updates its velocity based on the net force:

```python
body1.update_velocity(force_x, force_y, delta_time * time_factor)

```

Subsequently, all bodies update their positions using the newly computed velocities:

```python
body.update_position(delta_time * time_factor)

```

This first-order integration method provides computational simplicity suitable for educational purposes and real-time visualization, though it accumulates energy error over long simulation times.

### Visualization and Example Systems

The module includes Matplotlib-based animation through `FuncAnimation`, which repeatedly invokes `update_step` to advance physics calculations and reposition plotted circles. The repository provides three canonical example configurations:

- **Figure-8 Three-Body Solution**: Symmetric initial conditions producing a stable periodic orbit (`example_1`)
- **Earth-Moon System**: Realistic masses and distances with massive time-scaling to render orbital mechanics visible (`example_2`)
- **Random Many-Body Cloud**: Twenty bodies with paired opposite velocities to maintain zero net momentum (`example_3`)

## Analytical Physics Models

Beyond dynamical simulations, the repository contains deterministic algorithms that compute physical quantities using closed-form equations rather than iterative integration.

### Terminal Velocity Calculation

The [`physics/terminal_velocity.py`](https://github.com/TheAlgorithms/Python/blob/main/physics/terminal_velocity.py) module implements the analytical solution for an object falling through a fluid at steady state. The algorithm balances gravitational force, buoyancy, and drag to compute:

$$V_t = \sqrt{\frac{2mg}{\rho A C_d}}$$

This requires no time-stepping; the `terminal_velocity()` function accepts mass, fluid density, cross-sectional area, and drag coefficient, returning the constant terminal speed directly with input validation.

### Fluid Dynamics Parameters

Additional modules provide single-equation calculations for fluid and wave phenomena:

- **[`physics/reynolds_number.py`](https://github.com/TheAlgorithms/Python/blob/main/physics/reynolds_number.py)**: Computes dimensionless Reynolds number $Re = \frac{\rho v L}{\mu}$ to characterize flow regimes
- **[`physics/speed_of_sound.py`](https://github.com/TheAlgorithms/Python/blob/main/physics/speed_of_sound.py)**: Calculates wave propagation speed in gases based on temperature and specific heat ratio $\gamma$

## How to Run the Simulations

Execute the figure-8 three-body solution using the predefined example:

```python
from physics.n_body_simulation import example_1, plot

system = example_1()
plot("Figure‑8 solution", system, -2, 2, -2, 2)

```

Simulate the Earth-Moon system with realistic astronomical parameters:

```python
from physics.n_body_simulation import example_2, plot

system = example_2()
plot(
    "Moon‑Earth system",
    system,
    -4.3e8,
    4.3e8,
    -4.3e8,
    4.3e8,
)

```

Generate a random many-body gravitational cloud:

```python
from physics.n_body_simulation import example_3, plot

system = example_3()
plot("Random many‑body system", system, -1.5, 1.5, -1.5, 1.5)

```

Calculate terminal velocity for a spherical object falling through air:

```python
from physics.terminal_velocity import terminal_velocity

vt = terminal_velocity(mass=1.0, density=1.225, area=0.1, drag_coefficient=0.47)
print(f"Terminal velocity: {vt:.2f} m/s")

```

## Summary

- **[`physics/n_body_simulation.py`](https://github.com/TheAlgorithms/Python/blob/main/physics/n_body_simulation.py)** implements a complete gravitational N-body simulator using Newtonian mechanics, explicit Euler integration, and gravitational softening to prevent singularities.
- The simulation architecture separates physical entities (`Body`) from system management (`BodySystem`), enabling configurable initial conditions ranging from figure-8 orbits to planetary systems.
- **Analytical modules** like [`terminal_velocity.py`](https://github.com/TheAlgorithms/Python/blob/main/terminal_velocity.py), [`reynolds_number.py`](https://github.com/TheAlgorithms/Python/blob/main/reynolds_number.py), and [`speed_of_sound.py`](https://github.com/TheAlgorithms/Python/blob/main/speed_of_sound.py) provide direct equation implementations for fluid dynamics and mechanics without iterative time-stepping.
- All algorithms include input validation and example configurations that demonstrate how parameter changes affect physical outcomes, serving as educational references for computational physics implementation.

## Frequently Asked Questions

### What integration method does the N-body simulation use?

The N-body simulation in [`physics/n_body_simulation.py`](https://github.com/TheAlgorithms/Python/blob/main/physics/n_body_simulation.py) uses **explicit Euler integration**, a first-order numerical method where velocities are updated using current forces, followed by position updates using the new velocities. This method appears in the `update_velocity` and `update_position` methods of the `Body` class.

### How does the simulation prevent numerical singularities when bodies collide?

The algorithm implements **gravitational softening** through the `softening_factor` parameter added to the squared distance calculation. When computing $r = \sqrt{x^2 + y^2 + \epsilon}$, the softening term $\epsilon$ ensures the denominator never approaches zero during close encounters, preventing infinite force calculations.

### Can the physics simulations handle real-world scale like planetary orbits?

Yes, the Earth-Moon example (`example_2`) demonstrates real-world scale compatibility by using actual astronomical masses and distances (approximately $4.3 \times 10^8$ meters orbital radius). The `time_factor` parameter scales the simulation speed to make the orbital period visible, allowing realistic parameters to run at observable time rates.

### What is the difference between the N-body simulation and terminal velocity calculation?

The **N-body simulation** is a **dynamic, time-dependent model** that iteratively updates system states through numerical integration to show evolution over time. In contrast, the **terminal velocity calculation** is an **analytical, steady-state solution** that computes a single value using algebraic rearrangement of force-balance equations without iteration or time-stepping.