Skip to content

Instantly share code, notes, and snippets.

@mef51
Created October 11, 2016 16:57
Show Gist options
  • Save mef51/9a6828ef189de1369635c17471e64586 to your computer and use it in GitHub Desktop.
Save mef51/9a6828ef189de1369635c17471e64586 to your computer and use it in GitHub Desktop.
dinky simulation of earth sun system, storing here
#!/usr/local/bin/node
var simulateEarthSunSystem = function(){
var G = 6.67e-11;
var earth = {
x: 150e9, // m
y: 0,
radius: 6371e3, // m
m: 5.9e24, // kg
vx : 0, // m/s
vy : 30e3 // m/s
};
var sun = {
x: 0,
y: 0,
radius: 696e6, // m
m: 2.0e30, // kg
vx: 0, // m/s
vy: 0 // m/s
};
var gravity = function(obj1, obj2){
dx = obj2.x - obj1.x;
dy = obj2.y - obj1.y;
var r = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
var fMag = G * obj1.m * obj2.m / (r*r);
var fx = fMag * dx / r;
var fy = fMag * dy / r;
return {
fx: fx,
fy: fy
};
}
var log = function(d){console.log(d);}
var objects = [earth, sun];
var dt = 86400; // s
var t = 0; var maxT = 32000000; // s
var data = {}; // maps time in seconds to the positions and speeds of the sun and the earth
var updateData = function(t, earth, sun){
data[t] = {
earth: {
x: earth.x, // m
y: earth.y,
radius: earth.radius, // m
m: earth.m,
vx : earth.vx,
vy : earth.vy
},
sun: {
x: sun.x,
y: sun.y,
radius: sun.radius,
m: sun.m,
vx: sun.vx,
vy: sun.vy
}
};
}
for(var t = 0; t < maxT; t += dt){
updateData(t, earth, sun);
for(var i = 0; i < objects.length; i++){
var force = gravity(earth, sun);
var ax = force.fx / objects[i].m;
var ay = force.fy / objects[i].m; // (m/s)/s
// integrate the changes in speed
var dvx = ax * dt;
var dvy = ay * dt;
objects[i].vx += dvx;
objects[i].vy += dvy;
// integrate the changes in position
var dx = objects[i].vx * dt;
var dy = objects[i].vy * dt;
objects[i].x += dx;
objects[i].y += dy;
}
if(t+dt >= maxT){
updateData(t, earth, sun);
}
}
return data;
}
data = simulateEarthSunSystem();
console.log(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment