Skip to content

Instantly share code, notes, and snippets.

@nickstenning
Created March 28, 2010 19:06
Show Gist options
  • Select an option

  • Save nickstenning/346964 to your computer and use it in GitHub Desktop.

Select an option

Save nickstenning/346964 to your computer and use it in GitHub Desktop.
#include "particle.hh"
#include "simulator.hh"
using namespace std;
Particle::Particle(string n, const double m, Point x0, Arrow v0) : name(n), mass(m), x(x0), v(v0)
{}
void Particle::setSimulator(Simulator* sim)
{
simulator = sim;
}
Arrow Particle::computeAcceleration() {
Arrow accel, distance;
for (vector<Particle>::iterator p = simulator->particles.begin();
p != simulator->particles.end();
++p)
{
if (*p != *this) { // Don't calculate acceleration due to yourself!
distance = p->x - x;
accel += (C::G_scaled * p->mass * distance) / pow(distance.norm(), 3);
}
}
return accel;
}
bool Particle::operator==(const Particle& rhs) const
{
return (name == rhs.name);
}
bool Particle::operator!=(const Particle& rhs) const
{
return !(*this == rhs);
}
ostream& operator<<(ostream &os, const Particle& obj)
{
os << "<Particle " << obj.name << ">";
return os;
}
#ifndef PARTICLE_HH_
#define PARTICLE_HH_
#include "point.hh"
#include "constants.hh"
#include <cmath>
#include <vector>
#include <string>
#include <iostream>
class Simulator;
class Particle
{
public:
Particle(std::string name, double mass, Point x0, Arrow v0);
void setSimulator(Simulator* sim);
Arrow computeAcceleration();
bool operator==(const Particle& rhs) const;
bool operator!=(const Particle& rhs) const;
friend std::ostream &operator<<(std::ostream& os, const Particle& p);
private:
std::string name;
double mass;
Point x;
Arrow v;
Simulator* simulator;
};
#endif
#include "simulator.hh"
using namespace std;
Simulator::Simulator(string od) : outputDir(od)
{
if (outputDir.compare(outputDir.length() - 1, 1, "/") != 0)
{
outputDir.append("/");
}
// system(("mkdir -p " + outputDir).c_str());
}
int Simulator::run(double time)
{
double timestep = 1;
for (double t = 0; t < time; t += timestep)
{
step(t, timestep);
printTrajectories();
}
return 0;
}
void Simulator::step(double t, double dt)
{
cout << t << ": stepping " << dt << endl;
}
void Simulator::printTrajectories() {}
#ifndef SIMULATOR_HH_
#define SIMULATOR_HH_
// #include <gsl/gsl_errno.h>
// #include <gsl/gsl_matrix.h>
// #include <gsl/gsl_odeiv.h>
#include <vector>
#include <string>
#include "particle.hh"
class Simulator
{
public:
Simulator(std::string outputDir);
int addParticle(const Particle& p);
int run(double time);
void step(double time, double dt);
void printTrajectories();
friend class Particle;
private:
std::vector<Particle> particles;
std::string outputDir;
};
#endif /* SIMULATOR_HH_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment