One app I've always wanted to do was an n-body gravity simulator. Having recently discovered the <canvas> tag, I decided to whip up a quick naive simulator (won't work in IE, although this looks promising.):
(E is the total energy of the system, p is the linear momentum, and L is the angular momentum, all of which should be conserved. p and L hardly changes because conservation of momentum is equivalent to Newton's Third Law which is explicitly used in the simulation. This is probably why I've never seen them used as measures of accuracy, whereas E is very commonly used as such.)
Currently, it uses the classical Runge-Kutta method to integrate the equations of motion which preserves stability reasonably well. The current example, a star system with two planets and a moon, keeps its orbit for quite a few minutes before significantly degenerating. I plan to see if a higher-order or adaptive method might enable me to speed up the simulation with the same level of accuracy. I've also wanted to investigate symplectic integrators.
The Art of Computational Science was quite helpful in hashing out the details, despite being unfinished and a little rough. This page of n-body simulation methods provides a nice survey of the problem and its possible solutions. There are a few other gravity simulators out there in JavaScript that I used to get an idea of where to start, although I focused more on creating an accurate and robust simulation.
One thing I'm still hunting for is a good primer on optimizing JavaScript code for these types of applications, although I have little hope of finding anything since this is hardly a common use case for the language. I did some profiling early on and experimented with trying to avoid creating garbage in memory, although I didn't notice any significant gain.
Post a Comment