rk4-mech

1.0.0 • Public • Published

rk4-mech

Fourth order Runge-Kutta method implementation for mechanical systems simulation (physics engines).

Usage

rk4(p: [Number],
    v: [Number],
    a: function (p, v) { ... return [Number] },
    dt: Number,
    [pOut=p: []],
    [vOut=v: []])
  • rk4 function accepts initial position p, initial velocity v, a function that calculates acceleration a, time increment dt.
  • p and v are arrays (with the length equal to the number of spacial dimensions), a shold return an array.
  • If optional arguments pOut and vOut are not present the resulting position and velocity are written to p and v.

Very simple one-dimensional example:

const rk4 = require('rk4-mech')
let pos0 = [2]    // [m]
let vel0 = [16.6] // [m/s]
let accelFunc = function (/* ignore p and v */) {
  return [1]      // [m/s^2] constant acceleration 
}
let posOut = []
let velOut = []
let dt = 0.1
rk4(pos0, vel0, accelFunc, dt, posOut, velOut)
//posOut = p = p0 + v0*dt + a*dt^2/2 = 3.665 m
//velOut = v = v0 + a*dt = 16.7 m/s

Mass-spring one dimensional system:

let t = 0            // [s]
let dt = 0.01        // [s]
let m = 10           // [kg]
let l0 = 1           // [m]
let k = 2            // [N/m]
let p = [l0 - 0.5]   // [m]
let v = [0]          // [m/s]
let a = (p, v) => {
  let dl = p[0] - l0 // [m]
  let F = -dl * k    // [N]
  return [F / m]     // [m/s^2]
}
// simulate one half of oscillation period
while (v[0] >= 0) {
  t += dt
  rk4(p, v, a, dt)
}
console.log('final position: ' + p)
console.log('final velocity: ' + v)
console.log('expected T/2: ' + (Math.PI * Math.sqrt(m/k)) + ', actual: ' + t)

Package Sidebar

Install

npm i rk4-mech

Weekly Downloads

2

Version

1.0.0

License

MIT

Last publish

Collaborators

  • grabantot