I'm writing a sort of physical simulator. I have $n$ bodies that move in a two dimensional space under the force of gravity (for instance it could be a simplified version of the solar system). Let's call $m_1, \dots, m_n$ their masses, $(x_1, y_1), \dots (x_n,y_n)$ their positions, $(vx_1, vy_1), \dots (vx_n,vy_n)$ their velocities and $(ax_1, ay_1), \dots (ax_n,ay_n)$ their accelerations. Suppose we are given some initial conditions on the positions and velocities, and let $dt$ be a small amount of time. My goal is to compute the positions of all bodies at time $t_0+dt$, $t_0+2dt$, $\dots$ and so on, where $t_0$ is the initial time.
Here is what I have done:
- First I compute for all bodies the total force that acts at the current time on them, due to all other bodies. And so I compute the instantaneous acceleration for each body;
- Then I compute the new velocity for each body, by applying the formulas $vx_i \leftarrow vx_i + dt\cdot ax_i$ and $vy_i \leftarrow vy_i + dt\cdot ay_i$;
- Finally I compute the new position for each body, by applying the analogous formulas $x_i \leftarrow x_i + dt\cdot vx_i$ and $y_i \leftarrow y_i + dt\cdot vy_i$.
My solution in some sense remember me Euler method for solving differential equations. It is quite intuitive and simple, but rather accurate. What I am wondering is if there is a clever better method for solving the problem. For better I mean that, given a fixed $dt$, it can get closer to the exact solution by requiring equal or less computations.
For instance, if we interchange points 2. and 3., by experimentation, I noticed that we obtain a method which requires the same computations but is far less accurate (for it to be as accurate as the original method, we have to use a smaller step $dt$).
Runge-Kutta is a typical choice.
Also, I would highly recommend that you take a look at Introduction to Computer Simulation Methods. The book covers a wide range of topics relating to simulating physical phenomena, from solar systems to molecular diffusion to galaxies to chemical reactions, and more. I personally like the 2nd edition better than the 3rd edition, but that's a personal bias.
Another excellent resource for all things numerical is the celebrated Numerical Recipes series of books. You'll find ample and detailed discussion there about Runge-Kutta as well as lots of other material related to numerical methods.
Edit: if you're concerned about long-term conservation of energy then you might want to look at the Verlet integrator.