Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
integrate.html
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.