# N-body simulation

I have a made a fully functional n-body simulation for a project in high school, written in Java.

Right now, to "simulate" the solar system, I am simply spawning the different bodies at their respective distance from the sun with an initial velocity calculated by v = sqrt(G*M/r), as shown in the picture:
http://i.imgur.com/aJYLwRM.png where the earth is blue, mars is green and jupiter is red.

However, after a while, these bodies travel outwards and soon leave the screen (still maintaining an orbit, the radius of the orbit is just increasing.). Now I am wondering, is this bound to happen using newtons simplified formulas, or is it my program that is not functioning properly? Could it be that the orbits should not be exactly circular?

And another question: how can I use my simulation to actually simulate the orbits of the planets in ellipses? I have been trying to figure out a smart way to spawn the bodies, but I haven't been successful.

Any ideas? And sorry if this thread is in the wrong section, didn't really know where to put it.

DaveC426913
Gold Member
If you are inputting the distances and velocities with enough accuracy, you should not be getting circular orbits; you should be getting elliptical orbits. This causes me to wonder how your orbits are circular in your sim. Are you defining them as circular? I can see that being of concern, since it suggests that you're not really simulating gravity.

The usual way of doing such a (2D) sim is to define each point with 5 params: (x,y) position, (x,y) velocity, and mass. Give them those starting values. Apply the gravitational formula to each body in one step, then update the 4 changed params. Repeat ad infinitum.

As for wandering off-screen, there will always be some tiny inaccuracies in your sim because you must set a limit on the granularity (size of increments) in your position and velocity coordinates, and these have to be large enough that you can run through them each update-interval in real-time on a real machine. On a hypothetical, nigh-infinitely-fast machine, you could calc position and velocity down to 100 decimal places so your bodies would not stray. The inaccuracies are cumulative over time.

I did a sim in Java many years ago. I could add up to 20 bodies (more would render too slow to be useful) with a wide range in masses. In my sim, you added bodies with a mere click to place them where you wanted, and then a drag to set a velocity and direction. It was easy, but very clumsy at adding bodies with just the right orbital components to properly orbit another body.

Try as I might, I could never get a moon to orbit a planet which was in turn orbiting a stellar body.

I also had to add a fudge factor when two bodies got closer than a certain distance. Errors are greatly magnified at close range, and my smaller bodies would slingshot around the larger bodies and rocket off-screen at outrageous velocities to be lost forever in sim-space.

Last edited:
If you are inputting the distances and velocities with enough accuracy, you should not be getting circular orbits; you should be getting elliptical orbits. This causes me to wonder how your orbits are circular in your sim. Are you defining them as circular? I can see that being of concern, since it suggests that you're not really simulating gravity.

The usual way of doing such a (2D) sim is to define each point with 5 params: (x,y) position, (x,y) velocity, and mass. Give them those starting values. Apply the gravitational formula to each body in one step, then update the 4 changed params. Repeat ad infinitum.

As for wandering off-screen, there will always be some tiny inaccuracies in your sim because you must set a limit on the granularity (size of increments) in your position and velocity coordinates, and these have to be large enough that you can run through them each update-interval in real-time on a real machine. On a hypothetical, nigh-infinitely-fast machine, you could calc position and velocity down to 100 decimal places so your bodies would not stray. The inaccuracies are cumulative over time.

I did a sim in Java many years ago. I could add up to 20 bodies (more would render too slow to be useful) with a wide range in masses. In my sim, you added bodies with a mere click to place them where you wanted, and then a drag to set a velocity and direction. It was easy, but very clumsy at adding bodies with just the right orbital components to properly orbit another body.

Try as I might, I could never get a moon to orbit a planet which was in turn orbiting a stellar body.

I also had to add a fudge factor when two bodies got closer than a certain distance. Errors are greatly magnified at close range, and my smaller bodies would slingshot around the larger bodies and rocket off-screen at outrageous velocities to be lost forever in sim-space.

Thank you for a very informative reply. Ooh sorry, I think I didn't look close enough. They don't exactly look elliptical, but certainly not circular either. I am not defining how they should move :) Gravity does all the work. Here is a video of how they look, sorry for the quality . Notice how they begin to wander further and further from the sun. What causes this? Is it purely because of the inherent inaccuracies in the simulation? My simulation works exactly as you described.

What is a fudge factor? Is it the same as the gravitational dampener to hinder the distance between two bodies from reaching zero? Cause I just added a collision detection. Or why would it be more inaccurate close to another body?

However, after a while, these bodies travel outwards and soon leave the screen (still maintaining an orbit, the radius of the orbit is just increasing.).

That's a typical error of an Euler integrator. You need to use a better algorithm.

That's a typical error of an Euler integrator. You need to use a better algorithm.

Oh okay, finally I know why atleast. Do you know any easy method to fix it? Or which method should I use instead? Is it the energy that needs to be conserved? Keep in mind that I am only in high school and haven't got a great amount of programming experience

Do you know any easy method to fix it?

http://en.wikipedia.org/wiki/Leapfrog_integration

Is it the energy that needs to be conserved?

That's how Leapfrog works but integrators without energy conservation but with higher accuracy (such as Runge-Kutta-Nyström) work as well.

http://en.wikipedia.org/wiki/Leapfrog_integration

That's how Leapfrog works but integrators without energy conservation but with higher accuracy (such as Runge-Kutta-Nyström) work as well.

Okay, just to be clear. The mechanical energy of earth (kinetic and the potential energy to all other planets) is actually decreasing as time passes. It starts off being around 2*10^33 Joules and after about 20 seconds, it is 1*10^33 Joules. Is this problem big enough to cause the errors I am experiencing?

Is this problem big enough to cause the errors I am experiencing?

Of course it is. Your integrator is definitely not suitable for this simulation.

Of course it is. Your integrator is definitely not suitable for this simulation.

Okay, the project is due in two days, but I'll try to implement a leapfrog integrator. Hopefully it's not too hard.

But if my orbits are getting further and further away from the sun, shouldn't that be because of an excess energy in the bodies, not less?

Okay, the project is due in two days, but I'll try to implement a leapfrog integrator. Hopefully it's not too hard.

It's almost as easy as Euler.

But if my orbits are getting further and further away from the sun, shouldn't that be because of an excess energy in the bodies, not less?

Did you consider the sign of the potential energy?

It's almost as easy as Euler.

Did you consider the sign of the potential energy?

It is negative.

It currently looks like this. E_m = (mv^2 / 2) - (GMm / r)