public
Created

integrate.html

  • Download Gist
gistfile1.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
<html>
 
<head>
</head>
 
<body>
 
<script>
 
function State () {
this.x = null;
this.v = null;
return this;
}
 
function Derivative () {
this.dv = null;
this.dx = null;
return this;
}
 
function acceleration (state, t) {
var k = 10,
b = 1;
 
return - k*state.x - b*state.v;
}
 
/**
* @param {State} initial
* @param {number} t
* @param {number} dt
* @param {Derivative} d
*/
function evaluate (initial, t, dt, d) {
var state = new State();
var output = new Derivative();
 
if (typeof dt === 'undefined') {
output.dx = initial.v;
output.dv = acceleration(initial, t);
} else {
state.x = initial.x + d.dx*dt;
state.v = initial.v + d.dv*dt;
 
output.dx = state.v;
output.dv = acceleration(state, t+dt);
}
 
return output;
}
 
function integrate (state, t, dt) {
var a = evaluate(state, t),
b = evaluate(state, t, dt*0.5, a),
c = evaluate(state, t, dt*0.5, b),
d = evaluate(state, t, dt, c);
 
var dxdt = 1/6 * (a.dx + 2 * (b.dx + c.dx) + d.dx);
var dvdt = 1/6 * (a.dv + 2 * (b.dv + c.dv) + d.dv);
 
state.x += dxdt*dt;
state.v += dvdt*dt;
}
 
(function () {
var state = new State();
state.x = 100;
state.v = 0;
 
var t = 0;
var dt = 0.1;
 
while (Math.abs(state.x) > .001 || Math.abs(state.v) > .001) {
console.log(state.x, state.v);
integrate(state, t, dt);
t += dt;
}
} ());
 
</script>
 
</body>
</html>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.