Created
September 26, 2013 08:15
-
-
Save bellbind/6711271 to your computer and use it in GitHub Desktop.
[nodejs][javascript]numerical analysis of differential equations
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
// analysis of differential equations | |
// parameters | |
// f: differential equation dy/dx = f(x, y) | |
// y0, x0: initial values | |
// h: small value of diff x | |
// n: calc count, xn = x0 + n*h | |
var eular = function (f, y0, x0, h, n) { | |
var y = [y0], x = [x0]; | |
for (var i = 0; i < n; i++) { | |
y[i + 1] = y[i] + h * f(x[i], y[i]); | |
x[i + 1] = x[i] + h; | |
} | |
return {x: x, y: y}; | |
}; | |
// modified eular method | |
var eular2 = function (f, y0, x0, h, n) { | |
var y = [y0], x = [x0]; | |
for (var i = 0; i < n; i++) { | |
var d = y[i] + h * f(x[i], y[i]); | |
y[i + 1] = y[i] + h / 2 * (f(x[i], y[i]) + f(x[i] + h, d)); | |
x[i + 1] = x[i] + h; | |
} | |
return {x: x, y: y}; | |
}; | |
var rk4 = function (f, y0, x0, h, n) { | |
var y = [y0], x = [x0]; | |
for (var i = 0; i < n; i++) { | |
var k1 = f(x[i], y[i]); | |
var k2 = f(x[i] + h / 2, y[i] + h / 2 * k1); | |
var k3 = f(x[i] + h / 2, y[i] + h / 2 * k2); | |
var k4 = f(x[i] + h, y[i] + h * k3); | |
y[i + 1] = y[i] + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4); | |
x[i + 1] = x[i] + h; | |
} | |
return {x: x, y: y}; | |
}; | |
// example | |
var f = function (x, y) { | |
return x + 1; | |
}; | |
// dy/dx = x + 1 ==> y = 1/2 * x^2 + x + y0 | |
// check values | |
var c = {x: [0], y: [0]} | |
for (var i = 0; i < 10; i++) { | |
var x = 0.1 * (i + 1); | |
c.x.push(x); | |
c.y.push(1 / 2 * x * x + x); | |
} | |
//console.log(c.y); | |
// eular | |
var e = eular(f, 0, 0, 0.1, 10); | |
//console.log(e.y); | |
console.log(e.y.map(function (y, i) {return y - c.y[i];})); | |
// eular2 | |
var e2 = eular2(f, 0, 0, 0.1, 10); | |
//console.log(e2.y); | |
console.log(e2.y.map(function (y, i) {return y - c.y[i];})); | |
// runge kutta | |
var r = rk4(f, 0, 0, 0.1, 10); | |
//console.log(r.y); | |
console.log(r.y.map(function (y, i) {return y - c.y[i];})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment