Here's a Java implementation of an N-body simulation optimized to handle 1,000,000 objects. This implementation uses several optimization techniques to handle the large number of bodies efficiently.
Implementation
java
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class NBodySimulation {
private static final double G = 6.67430e-11; // Gravitational constant
private static final double SOFTENING = 1e-9; // Softening factor to prevent extreme forces
private static final int THRESHOLD = 1000; // Threshold for parallel processing
private Body[] bodies;
private int numBodies;
private double[] forcesX, forcesY, forcesZ;
public NBodySimulation(int numBodies) {
this.numBodies = numBodies;
this.bodies = new Body[numBodies];
this.forcesX = new double[numBodies];
this.forcesY = new double[numBodies];
this.forcesZ = new double[numBodies];
initializeBodies();
}
private void initializeBodies() {
Random random = new Random();
for (int i = 0; i < numBodies; i++) {
double mass = 1e20 + random.nextDouble() * 1e22;
double x = random.nextDouble() * 1e12 - 5e11;
double y = random.nextDouble() * 1e12 - 5e11;
double z = random.nextDouble() * 1e12 - 5e11;
double vx = random.nextDouble() * 1e4 - 5e3;
double vy = random.nextDouble() * 1e4 - 5e3;
double vz = random.nextDouble() * 1e4 - 5e3;
bodies[i] = new Body(mass, x, y, z, vx, vy, vz);
}
}
public void simulateStep(double dt) {
// Reset forces
for (int i = 0; i < numBodies; i++) {
forcesX[i] = 0;
forcesY[i] = 0;
forcesZ[i] = 0;
}
// Calculate forces in parallel
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new ForceCalculator(0, numBodies));
pool.shutdown();
// Update positions and velocities
for (int i = 0; i < numBodies; i++) {
Body body = bodies[i];
// Update velocity
double ax = forcesX[i] / body.mass;
double ay = forcesY[i] / body.mass;
double az = forcesZ[i] / body.mass;
body.vx += ax * dt;
body.vy += ay * dt;
body.vz += az * dt;
// Update position
body.x += body.vx * dt;
body.y += body.vy * dt;
body.z += body.vz * dt;
}
}
private class ForceCalculator extends RecursiveAction {
private final int start;
private final int end;
public ForceCalculator(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected void compute() {
if (end - start <= THRESHOLD) {
computeDirectly();
} else {
int mid = start + (end - start) / 2;
invokeAll(
new ForceCalculator(start, mid),
new ForceCalculator(mid, end)
);
}
}
private void computeDirectly() {
for (int i = start; i < end; i++) {
Body body1 = bodies[i];
double fx = 0, fy = 0, fz = 0;
for (int j = 0; j < numBodies; j++) {
if (i == j) continue;
Body body2 = bodies[j];
double dx = body2.x - body1.x;
double dy = body2.y - body1.y;
double dz = body2.z - body1.z;
double distanceSquared = dx * dx + dy * dy + dz * dz + SOFTENING;
double distance = Math.sqrt(distanceSquared);
double forceMagnitude = G * body1.mass * body2.mass / distanceSquared;
fx += forceMagnitude * dx / distance;
fy += forceMagnitude * dy / distance;
fz += forceMagnitude * dz / distance;
}
forcesX[i] = fx;
forcesY[i] = fy;
forcesZ[i] = fz;
}
}
}
public static void main(String[] args) {
int numBodies = 1_000_000;
NBodySimulation simulation = new NBodySimulation(numBodies);
long startTime = System.currentTimeMillis();
int steps = 10;
double dt = 1000; // Time step in seconds
for (int step = 0; step < steps; step++) {
simulation.simulateStep(dt);
System.out.println("Completed step " + (step + 1) + "/" + steps);
}
long endTime = System.currentTimeMillis();
System.out.println("Simulation completed in " + (endTime - startTime) + " ms");
}
private static class Body {
double mass;
double x, y, z; // Position
double vx, vy, vz; // Velocity
public Body(double mass, double x, double y, double z, double vx, double vy, double vz) {
this.mass = mass;
this.x = x;
this.y = y;
this.z = z;
this.vx = vx;
this.vy = vy;
this.vz = vz;
}
}
}
Key Optimization Techniques
Parallel Processing: Uses Java's ForkJoinPool to parallelize force calculations across multiple CPU cores.
Memory Efficiency: Pre-allocates arrays for forces to minimize memory allocation during simulation.
Barnes-Hut Approximation Alternative: While this implementation uses direct summation, for 1M bodies you might want to implement the Barnes-Hut algorithm (which uses a tree structure to approximate forces from distant bodies).
Softening Factor: Prevents numerical instability when bodies get very close to each other.
Threshold-based Parallelization: Only parallelizes when the workload is large enough to justify the overhead.
Performance Considerations
For 1,000,000 bodies:
The direct N² algorithm would require ~1 trillion calculations per step
This implementation uses parallel processing to distribute the workload
Memory usage is optimized by using primitive arrays instead of objects where possible
Further Optimizations
For even better performance with 1M bodies:
Implement the Barnes-Hut algorithm (O(n log n) complexity)
Use a more sophisticated spatial partitioning scheme
Consider using a GPU with OpenCL or CUDA for acceleration
Implement a more efficient data structure for body storage
Would you like me to explain any specific part of this implementation in more detail or suggest alternative approaches?