# Create an Orbital Simulator

## Main Question or Discussion Point

I am toying with the idea of creating a general orbital simulator. Possibly lacking the proper terminology, here is a basic description of my goal, make that wild dream.

Step 1. Working in 2 dimensions, user enters the mass of 1 to N object, their initial position, their initial velocity, and a time calculation interval. For each time interval, the simulator calculates the forces that each body applies to each other body, the summed vector of that force, applies it to the initial velocity, and determine the position at the end of the time interval. It then shows the position of each body. Repeat.

Step 2. Add niceties like lines showing where each body has been for some number of iterations so we can better see the activity.

Some future step, make it three dimensional.

This seems a rather ambitious project so before I start:
Do you know of any simulators of this nature?
Do you have any advice for a novice in celestial mechanics?
Do you think this would be better to attempt on Microsoft Windows or under Linux, I have both.

Thank you.

Related Computing and Technology News on Phys.org
Nabeshin
I contemplated doing this but found it to be beyond my current physics (and probably computer programming) abilities. I'd be really interesting to know the method you use to accomplish all this!

D H
Staff Emeritus
Step 1. Working in 2 dimensions, user enters the mass of 1 to N object, their initial position, their initial velocity, and a time calculation interval. For each time interval, the simulator calculates the forces that each body applies to each other body, the summed vector of that force, applies it to the initial velocity, and determine the position at the end of the time interval. It then shows the position of each body. Repeat.
This approach will work fine with one object. The object will move in a straight line because there no forces act on it. This approach will not work very well with two or more objects. The approach you outlined is called the Euler method for solving an initial value problem (i.e., a system whose complete system state is known at some point and whose evolution is described by a set of ordinary differential equations). The Euler method is very simple to implement but unfortunately does an incredibly lousy job except for the simplest of systems.

Fortunately, a lot of numerical integration techniques exist that do yield good accuracy. They are all more complex than the Euler method, but many are only a bit more complex. A couple of nice balances between complexity and accuracy are the velocity verlet technique, which is widely favored in chemistry simulations, and the fourth-order Runge-Kutta (RK4) technique, which is widely favored in orbital simulations. A quick google on velocity verlet and Runge-Kutta will yield a lot of information.

Hello D H,
We quickly delve into the reasons for my post. I don’t understand why the use of the simple equations f = ma, and f = ( G * M1 * M2 ) / r squared will not work. Comparing two bodies, there is a force between them that will change their velocity. If the masses and velocities are anywhere close to “right” then the two masses should orbit. Assume I iterate fast enough to get sufficient resolution but slow enough to prevent thrashing with no results. I will probably start with a resolution of one hour, 8,760 iterations will simulate a year on the scale of our solar system.

I looked at Runge-Kutta on Wiki and do not understand it at all. I am not trying to predict or smooth our trajectories, just create an instance and calculate the values for the next instance.

My first hurdle will be how to express mass in an equation. I will be looking that up.

Thanks for taking the time to reply.

Runge Kutta, Burlish Stoer, and Euclid

Both bkelly and DH are correct. If you use small timesteps (but very very small ones), the basic f=ma for N^2 interactions, will produce a proper simulation. But if two objects in that N body simulation *ever* approach closely enough so that the time-space resolution causes "thrashing" or a large error term in the step wise calculation, the simulation will only be characteristically correct, but will diverge greatly from reality. For the solar system, at a one hour resolution, you should have no problems for the solar system.

Runge-Kutta (RK) methods do not calculate smoothed out orbital calculations, or predictions, per-se. Rather, the multiple differnce terms you see in Runge-Kutta calculations, are for calculaing a quadratically accurate polynomial *approximation* of the orbit. Euler only calculates a first order polynomial *approximation* of the orbit.

Please read about Taylor series, rectangular integration rule, simpson's rule of integration, Euler method, and RK method, in detail and trials in code, to understand how Euler method, is like a first order rectangular integration, and RK on the fourth order method, is somewhat-like simpson's rule that calculates mini-chained parabolic integrals each step of the second order. It all has to do with the infinite Taylor series, and error terms of asymptotic convergent functions like gravitational fields. With RK, you could make the steps 3-5 days long, and be far more accurate with Mercury and close approaching comets, than you would using the Euler method. RK even comes in higher order methods that let you further increase the step size, as each step is even higher order accurate, with an exponentially shrinking residue in the Taylor series like infinite series. Trust me, if you learn RK, you will never regret it. Numerical Recipies in C, by Press, Teukolsky, et al, is a good book with such algoritms available in ready to use C code for either Linux or Microsoft C compiler environments.

Another method you may want to consider, if RK is too complex, is to use Burlish-Stoer (BS) methods. In short, first, you can take Euler method at 16 hours*1 step, 8*2, 4*4, 2*8, and 1 hours*16 step. Then do a least squares fitting of the 5 exponential refined ranges to extrapolate the asymptotic-convergent value using an appropriate asymptotic function, which you can vary it's parameters, until it fits the projected 16, 8, 4, 2, 1 series to find the convergent value at "0 hours". Then take that convergent value and take the 16 hour step at the infinitessimally projected 16 hour time step, using the asymptotic (0 hours*infinite step) projected step with approximated "perfect" precision. You will have to find the right equation for this application for the least squares fitting of the exponential approximations, and make sure the exponential ranged projections are not oscilatory, but asymptotic, so that the curve fitting is always accurate each step.

Incidentally, make sure any Euler, RK, or BS curve fit and planetary position and velocities are all done in double precision, and even then, that your numbers retain large precision in the LSB of the numbers. Study the IEEE (754) format for float and the one for doubles, paying special attention to the mantissa for precision checking. The Euler method, especially, if the time steps are too small, may become susceptible to quantization errors in extreme distance or closeness calculations, without checking precision in the mantissa. RK is the best, and BS can be used intermediately.

Last edited:
Step 1. Working in 2 dimensions, user enters the mass of 1 to N object, their initial position, their initial velocity, and a time calculation interval. For each time interval, the simulator calculates the forces that each body applies to each other body, the summed vector of that force, applies it to the initial velocity, and determine the position at the end of the time interval. It then shows the position of each body. Repeat.
I wrote an 3D, N-body orbital simulator, with displayed output, in basically the same manner you outline. Variables were updated, for the most part, in parallel. The model suffered orbits that would gradually increase in radius over iteration. I repaired it by breaking the parallel-set rule. Near collisions introduced a problem that I never did fix before loosing interest. A close approach would throw the two bodies out towards infinity. I attempted a conservation-of-energy kludge to fix the problem. It was a bust.

Wow, that was a lot to say. This will be more complicated that I imagined, even considering that I knew it would be more complicated than I knew. (Does anyone know of a happy face icon with a recursive grin?)

Simulating a solar system would be nice, but what I really want is the ability to start up a simulation with 3 or more stars in orbit around each other and see what happens. As noted by LoneDragon, that will involve some close approaches, high velocities, and obviously some time-space alterations (as compared to our perceptions of what is normal).

After reading Phrak’s post, I had best expect some anomalies in the behavior.

My thought is to use C++ or C# and create a class for celestial objects. For each body in a simulation, instantiate an object giving it the requisite mass, size, location, and velocity. (and other things I don’t know about yet.) The class would have a method that takes as its input parameter a pointer to another object. That method would then compare the parameters of the two bodies and calculate the resultant force at that point in time. In doing so, it would calculate the position and velocity for some specified time in the future. That time would be variable and should probably decrease based on distance, velocity, and I don’t know what else.

It seems like if I start it simple without close approaches, then when I get the mechanics of being able to calculate the resultant vectors of two bodies, and displaying an image of the bodies, then I can refine the equation within the class to any degree I want. Obvious performance will suffer, but that is the way it goes.

That reminds me. Back in the 1980s I created a program to display views of the Mandelbrot set. (This was when the standard speed was 4 MHz and a fast machine was 8 MHz.) I quickly had to use the 8087 for precision and speed. Using Turbo Pascal, I then dropped into assembly language to program the 8087 for speed and more accuracy. Finally when that was not enough resolution, I wrote some 128 bit fixed point arithmetic routines in assembly language and ran that. I never did find the threads between what appeared to be islands of points within the set.

But I digress.

I have seen images from simulations for galaxies, but I don’t know of any right now. It would be interesting to know how they ran those simulations, on what machines, what language, and how long it tool. A bit of searching is in my immediate future.

D H
Staff Emeritus
Both bkelly and DH are correct. If you use small timesteps (but very very small ones), the basic f=ma for N^2 interactions, will produce a proper simulation.
No, it won't. I work in this field and we have very explicit rules barring the use of the Euler method. The basic problem is that the Euler method conserves neither angular momentum nor energy. (RK4 has this problem too, but the error is vastly diminished compared to the Euler method.)

When writing any simulator, it is always a good idea to verify and validate the resultant simulation. One way to do this is to apply simulation to a case where the correct answer can be computed analytically. The case of 2 bodies has an analytical solution in Kepler's laws. The simplest case is two bodies in circular orbits about each other. The problem with the Euler method becomes apparent in this simple simulation: The bodies spiral away from one another. One can reduce the error by taking very small steps. Suppose you place two bodies in circular orbits about each other, simulate for what should be ten orbits, and examine the relative position error. To get a relative error of 1% or smaller, an Euler integrator would have to divide that 10 orbit time interval into well over 3 million subintervals. In comparison, an RK4 integrator would only need to divide that 10 orbit time interval into about 400 subintervals. Achieving a relative error of less than 0.1% requires about 900 subintervals for RK4 and is simply unachievable with Euler integration. The problem is that as one makes the time steps smaller and smaller, at some point the error starts to grow because (1+10-16)-1 = 0 using the ordinary double-precision arithmetic available on almost all computers now. Make the steps too small and the state freezes.

RK4 is not the be-all and end-all of numerical integration techniques. It is the most widely-used numerical integration technique because it is easy to implement and offers fairly good accuracy. There are more complex Runge-Kutta techniques that do a much better job than RK4. For example, a Runge-Kutta-Feldberg 7/8 integrator achieves better than 10-12 relative accuracy for the 10 orbit scenario described above by dividing the 10 orbit interval into about 1000 intervals. In comparison, a RK4 integrator run with the same time step will achieve a relative accuracy of about 5*10-5. The relative error with the Euler method at this coarse step size is greater than one. There are other more advanced techniques that do much, much better than any Runge-Kutta integrator.

Last edited:
what LD doesn't tell you is that all n-body sumulations are only characteristically correct. how correct you want yours depends upon your intent in doing the simulation.
If you want some initial results you don't need polynomial approximations.
btw, a break-down at close approach is characterised by the displacements obtained between iterations per the radial displacement between objects (rather than the radius you assign the objects).

what LD doesn't tell you is that all n-body sumulations are only characteristically correct. how correct you want yours depends upon your intent in doing the simulation.
If you want some initial results you don't need polynomial approximations.
btw, a break-down at close approach is characterised by the displacements obtained between iterations per the radial displacement between objects (rather than the radius you assign the objects).
Actually, I did. All taylor series family like methods are asymptotic approximations, with an error residue. More than once I referred to approximation, error residue, and close approach gross errors.

LD: It all has to do with the infinite Taylor series, and error terms of asymptotic convergent functions " sums all of this the best, and even higher order terms like RK4 or RK6 or RK... predictor corrector methods are all approximations. My one "proper" simulation remark, only refers to a simulation like the solar system where things don't get too close to each other and are near circular orbits, excluding moons. A complex stellar environment, with many close approaches, agreed, does require the more precise methods, like RK4 or RK6 and so forth. All of them do not preserve everything, if you want to be technical, as nearly all natural three-body problems are analytically unsolveable, and N body too.

For bkelly,
For an approximation-near-analytic text, to test a simulation of yours, there are astronomical ephemerides, with heliocentric velocity and position information. JPL has online ephemerides which may also be used to test your method, before doing complex N body stellar simulations, with close approaches, which will require higher order terms, near-accuracy methods.

Wow. This is beginning to sound like an incredibly complex task. I don't know enough to really understand what you guys are saying, but I will continue looking to determine the odds of getting something running that remotely resembles what would happen in reality.

Going to www dot ask dot com (this thing seems to tell me I cannot post a URL so I "said" it instead) and asking what are ephemerides yeilds nothing useful. A google search tells me that they give the location of satellites for each day of the year. Haveing been a systems engineer tracking rocket launches and using tracking antennas, I know what a TLE is. The JPS site appears beyond me, but I will wander around there and see what I can understand.

However, to my knowledge, I don't want to predict anything. I want to run a simulation that takes steps based on the current conditions and calculates movements to the next position or iteration.

However, again, as I alluded earlier, I am vaguely aware of the severe limits of my knowledge in this field. The core question has become:
Concerning the task of creating a basic orbital or stellar simulator, providing the ability to designate a known starting point for each of N bodies such as stars: How difficult will it be to get something that reasonably approximates how two to a dozen stars or planets will orbit each other? This is just the mathematics of it all and ignores the problems of display on a computer screen.

Ephemeris and Euler = RK1 for testing character.

Try Wikipedia. An astronomical ephemeris (blue books in the library for an american ephemeris I remember for each year) simply lists the positions and velocities of planets, and many other astronomical tables. For a test...

Euler method will *characteristically* work fine for you if all of the bodies don't have close elliptical approaches with large velocities that go though large angles in one step, which integrate increasingly improperly under those conditions in product. Then, if you have properly designed the input mass-position-velocity matrix, and next-step output mass-position-velocity matrix, and Euler step algorithm, and are happy you have worked out the bugs, you **may** replace the Euler test method step calculator, once you see initial Euler results, with a better algorithm. Modularity being key here.

Your code will work fine-enough, but inaccurately, so long as you are not trying to accurately predict, say, precise galactic arm characters, or precise galactic collision simulations.

Also, you can make a stop-gap measure that reduces the step size of close, high velocity, high angle around other body masses, by reducing the step size for *only* those bodies, leaving all of the other bodies at their normal step size. This is what is called an adaptive step size algorithm.

Incidentally, interestingly for the mathematicians only I guess, is that in the differential equations classifications, Euler's method is a first order RK, a second order modified Euler method is a second order RK (RK2), RK4 is obviously a fourth order RK and is closely related to the conceptually easy to understand Simpson's Rule for integration when done in one dimension, and there are higher order RK with more Taylor series expansion terms. But you can start with RK1 (Euler) and work your way up as you pick up the math.

I hope your simulation works well enough for you. I remember doing a solar system simulation on a commodore 64 in junior high which was alot of "fun" (please don't calculate my age) *grins*. Do make sure to calculate all of the bodies at once, from input array to output array in ping pong buffers, for if you advance through just one array and place the answers back in the array for the next step, it causes even more errors in a simple characteristic simulation as half the bodies are advanced, say, while the others are distorted in their interactions. To save time from memory swapping, just toggle referencing the ping pong buffers input-output back and forth with pointers, if your using C. C#, yer on yer own!

regards

Man you guys are smart. I too hope to become as smart as you guys one day. As of Right now I will use the excuse of being young. hehe

Man you guys are smart. I too hope to become as smart as you guys one day. As of Right now I will use the excuse of being young. hehe
LOL. Just study hard, read *everything* you can, and take whatever classes are possible *while paying attention*. Time will do the rest. But join the club, as I couldn't even multiply numbers until 3rd grade (I know, that sucks bad) ... hmmm, there must have been something in the water, causing the math spurt over the decades since *then*. LOL, then groans at self.

For bkelly:
To reiterate, as an engineer, I can say Euler will "git 'er done", for a quick peek at simulation programming, sufficient for a *basic* gravitation simulation, but with a strong emphasis on the *basic* simulation. So, "caveat emptor", or, "let the buyer beware", if this is a college math, and coding precision test,, versus a high school, personal interest, or introductory simulation level project. Still, it is good to study the other stuff, if you have the time, when regarding a related technical career.

Man you guys are smart. I too hope to become as smart as you guys one day. As of Right now I will use the excuse of being young. hehe
Hey! Don't include me in this catagory. I'm not BSing my way over someones head to give my gotta-be-smart-ego a plateform. But, hey, I could give it a whirl I 'spose. Let's all meet for tea on friday and we'll try it again.

Last edited:
Redbelly98
Staff Emeritus
Homework Helper
I wrote an 3D, N-body orbital simulator, with displayed output, in basically the same manner you outline. Variables were updated, for the most part, in parallel. The model suffered orbits that would gradually increase in radius over iteration. I repaired it by breaking the parallel-set rule. Near collisions introduced a problem that I never did fix before loosing interest. A close approach would throw the two bodies out towards infinity. I attempted a conservation-of-energy kludge to fix the problem. It was a bust.
Too bad yours didn't work out. I did something similar (in Visual Basic, on a Windows PC) 3 or 4 years ago and was reasonably happy with the results. I remember modifying the force so that it didn't diverge when the bodies got too close to each other, for the reason you saw: all hell breaks loose otherwise. Of course that meant some inaccuracies in the trajectories, but for example I was able to give a cool demonstration of the gravity-assist technique for boosting satellites.

If you're interested I can try to look up exactly how I did the modification to the force.

FYI, I only worked with up to 10 or 20 objects at a time, the computations really bogged down beyond that (Remember, this was Windows and Visual Basic).

Hey! Don't include me in this catagory. I'm not BSing my way over someones head to give my gotta-be-smart-ego a plateform. But, hey, I could give it a whirl I 'spose. Let's all meet for tea on friday and we'll try it again.
Well, I am curious for some enlightenment, as you're speaking above *me*, now. Where are the inaccuracies, in the long list of posts, on this thread? Everyone seems to be on an even keel, as far as I can tell, in my humble engineer's math. I see you are an aerodynamics student, or engineer, from your other posts, so, sir, you can take a whirl if you know *that* level of simulation math, as I, at least, would like to know your own numerical opinions, and knowledge, to correct the errant information on this thread. You know, so that we may all be made higher.

Redbelly98
Staff Emeritus
Homework Helper
Wow, that was a lot to say. This will be more complicated that I imagined, even considering that I knew it would be more complicated than I knew. (Does anyone know of a happy face icon with a recursive grin?)
Maybe the best thing right now is to use some basic algorithm, that you can easily understand, to get something working first. Then worry about making it more accurate or complex as a later project.

I found a simulator here: http :// kornelix . squarespace . com / galaxy /
(it seems I don't have URL priviledge, but google on "stellar simulation")
It runs under Linux so I fired up that computer and installed it. It runs well, but not much in the way of features. I haven't reviewed the code closely, but it seems to just use the F=MA type of approach. If I can get version 1.0 running, then I can look into better accuracy for close approaches.

There are two primary segments of this projects
Calculating the positions
Displaying the field
In this forum I want to discuss the calculations.

What type of coordinate system would be best, polar, Cartesian, or something else I don't know about? It seems to me that Cartesian would be better. If for no other reason, I have never messed with polar coordinates. But if polar would be much better, I would like to know.

If Cartesian, I suspect that it would be easier to deal with if the origin is in one of the corners rather than in the middle. My first thought would be the lower left corner. Thoughts about selecting the range: Astronomical Units, millions of miles, something else?

BTW: This site seems to respond much faster under Linux with Firefox than under XP with IE-7.

Too bad yours didn't work out. I did something similar (in Visual Basic, on a Windows PC) 3 or 4 years ago and was reasonably happy with the results. I remember modifying the force so that it didn't diverge when the bodies got too close to each other, for the reason you saw: all hell breaks loose otherwise. Of course that meant some inaccuracies in the trajectories, but for example I was able to give a cool demonstration of the gravity-assist technique for boosting satellites.

If you're interested I can try to look up exactly how I did the modification to the force.

FYI, I only worked with up to 10 or 20 objects at a time, the computations really bogged down beyond that (Remember, this was Windows and Visual Basic).
bkelley's the one you want to talk to about code. I wrote mine a few moons ago before they has invented rocks. Did you solve or notice the walk-away problem where circular orbits are really outward spirals? You can check if it's happening with a running total-energy value.

I hope I didn't PO lonedragon excessively...

Redbelly98
Staff Emeritus
Homework Helper
bkelly,

In Cartesian coordinates it's easier to convert from the (x,y) calculated positions to displayed pixel locations, as only simple scaling factors are involved. Might also be easier to put the origin at pixel (0,0) in the display in the upper left, but if you don't it's still pretty straightforward to rescale from (x,y) to pixel location.

I remember an algorithm a former physics teacher gave me. Better than Euler, not as accurate as Runge-Kutta, but pretty straightforward in terms of understanding it.

In 1-D it works like this ...

Do a Taylor series expansion to find $$x_{n+1}$$ given $$x_n$$ , where $$x_n = x(n \cdot \Delta t)$$ :

$$x_{n+1} = x_n + v_n \cdot \Delta t + \frac{1}{2} a_n \cdot \Delta t^2 + \frac{1}{6}x'''_n \cdot \Delta t^3 +$$ ...

Similarly,

$$x_{n-1} = x_n - v_n \cdot \Delta t + \frac{1}{2} a_n \cdot \Delta t^2 - \frac{1}{6}x'''_n \cdot \Delta t^3 +$$ ...

where $$v_n, a_n, x'''_n$$ are the velocity, acceleration, and 3rd derivitive of x, respectively, at time $$t= n \cdot \Delta t$$

$$x_{n+1} + x_{n-1} = 2 \cdot x_n + a_n \cdot \Delta t^2 +$$ ...

or

$$x_{n+1} = 2 \cdot x_n - x_{n-1} + a_n \cdot \Delta t^2 +$$ ...

Note the cancellation of the odd-order terms, so that the error is actually of order $$\Delta t^4$$, not $$\Delta t^3$$. All you need to calculate $$x_{n+1}$$ are the previous 2 values of x, as well as the acceleration at time $$n \cdot \Delta t$$, which you calculate from the Forces and masses in the system.

In 2-D you'd need to calculate the x- and y-components of the accelerations, then apply the algorithm to find $$x_{n+1}$$ and $$y_{n+1}$$ .

There might be a common name for this algorithm, if anybody knows it feel free to post the info.

Last edited:
Redbelly98
Staff Emeritus
Homework Helper
bkelley's the one you want to talk to about code. I wrote mine a few moons ago before they has invented rocks. Did you solve or notice the walk-away problem where circular orbits are really outward spirals? You can check if it's happening with a running total-energy value.
I didn't check circular orbits, that would have been a good test. What I did notice was that if two objects got very close, they could suddenly go flying off the screen at incredibly high speed.

p.s. I just looked over my code, and found that I used the algorithm I described in message #21. Somehow I thought I later changed this to Runge-Kutta but apparently not.
I can't figure out, from a quick glance at the code, just what I'm doing to the force to make it "behave" at close range. I would have to find some 3-year-old handwritten notes that I have somewhere to figure that out again.

Anyone feel like sharing one of their simulators? Would be interesting.

The guys at NASA, NSA, and whoever, should have devoted quit a few man-years at this. So they may have found a different method than interating t, and updating V_i and X_i. There's the Hamiltonian, if you've heard of it. It's an alternative, equivalent to Newtonian mechanics. What I'm trying to say, is that it may be possible to iterate values in some other mathematical space, rather than velocity and position. Angular momentum and Kinetic energy perhaps; I have no idea really. Just offinging possibilities.

D H
Staff Emeritus
I wrote an 3D, N-body orbital simulator, with displayed output, in basically the same manner you outline. Variables were updated, for the most part, in parallel. The model suffered orbits that would gradually increase in radius over iteration.
This is a direct consequence of using the Euler method. The Euler method displays this problem even with two bodies and even without any eccentricity.

I remember an algorithm a former physics teacher gave me. Better than Euler, not as accurate as Runge-Kutta, but pretty straightforward in terms of understanding it. ... There might be a common name for this algorithm, if anybody knows it feel free to post the info.
The method you described is the basic verlet method. As you noted, it is better than Euler. An even better approach and still very simple to understand is Heun's method.

I found a simulator here: http:// kornelix.squarespace.com/galaxy/ [Broken]. It runs well, but not much in the way of features. I haven't reviewed the code closely, but it seems to just use the F=MA type of approach.
The cited simulator updates the velocity and then updates the position using the updated velocity. This is not a very good integrator. A simple improvement is to update the position using the average of the velocity before and velocity after the velocity update. This simple improvement is Heun's method, a second-order Runge-Kutta integrator. Heun's method is considerably better than the midpoint method, another second-order Runge-Kutta integrator.

I haven't reviewed the code closely, but it seems to just use the F=MA type of approach.
*All* of the Runge-Kutta techniques as well as the verlet method "just use the F=Ma" type of approach. Some just do it a lot better than others.

I didn't check circular orbits, that would have been a good test.
That is always a good test. A simulator that can't do a very good job reproducing a circular orbit isn't worth very much at all. Highly elliptical orbits and hyperbolic orbits are also good tests because the close approaches will stress even good integrators.

Last edited by a moderator: