Skip to content

Instantly share code, notes, and snippets.

@xZise
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xZise/8729895 to your computer and use it in GitHub Desktop.
Save xZise/8729895 to your computer and use it in GitHub Desktop.
n-body halving example
class CelestialBody {
double mass;
QVector3D position;
QVector3D velocity;
QVector3D f[];
}
// …
for (int i = 0; i < bodies.length; i++) {
for (int j = 0; j < bodies[i].f.length; j++) {
bodies[i].f[j] = new QVector3D(0, 0, 0);
}
}
CelestialBody[] bodies;
for (int i = 0; i < bodies.length; i++) {
CelestialBody current = bodies[i];
double mu = G * current.mass;
for (int j = i + 1; j < bodies.length; j++) {
CelestialBody body = bodies[j];
QVector3D direction = body.position[r] - current.position[r];
double distanceSquared = direction.lengthSquared();
QVector3D f = (mu * body.mass / distanceSquared) * direction.normalized();
current.f[threadIndex] += f;
body.f[threadIndex] -= f;
}
}
for (int i = 0; i < bodies.length; i++) {
CelestialBody current = bodies[i];
QVector3D f = new QVector3D(0, 0, 0);
for (int j = 0; j < current.f.length; j++) {
f += current.f[j];
}
QVector3D a = f / current.mass;
current.velocity[w] = current.velocity[r] + (a * time);
current.position[w] = current.position[r] + (current.velocity[w] * time);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment