Created
February 24, 2017 01:47
-
-
Save zhantongz/c64c81654916542929207e51aa6e83c2 to your computer and use it in GitHub Desktop.
A very very very simple velocity-Verlet algorithm for a particle under harmonic potential
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var k, m, pos0, vel0, PREC; | |
PREC = 1e-5; // tolerance for float num | |
k = 1.0; // potential(x) = k * x^2 / 2 | |
m = 1.0; // mass | |
pos0 = 1.0; // init condition pos(0) | |
vel0 = 1.0; // init condition vel(0) | |
var equalZero = function(n) { | |
if (n === 0 || ((n < PREC) && (n > -PREC))) return true; | |
else return false; | |
} | |
var force = function(t, dt) { | |
console.log(`force(${t}, ${dt})`); | |
return k*pos(t - dt, dt); | |
} | |
var pos = function(t, dt) { | |
console.log(`pos(${t}, ${dt})`); | |
if(equalZero(t)) return pos0; | |
else return pos(t - dt, dt) + vel(t - dt, dt)*dt + force(t, dt) / (2 * m) * dt * dt; | |
} | |
var vel = function(t, dt) { | |
console.log(`vel(${t}, ${dt})`); | |
if(equalZero(t)) return vel0; | |
else return vel(t - dt, dt) + dt / (2 * m) * (force(t, dt) + force(t + dt, dt)); | |
} | |
q = [ | |
pos(0.1, 0.1), | |
vel(0.1, 0.1), | |
pos(0.2, 0.1), | |
vel(0.2, 0.1), | |
]; | |
console.log(q); // [ 1.105, 1.10525, 1.22105, 1.2215525 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment