Programming Assignment 9|
Write a program that simulates the motion of N bodies, mutually affected by gravitational forces, in a two-dimensional space. The time evolution of such systems are usually too complex to compute analytically, but scientists have made significant research contributions (in plasma physics, semiconductors, fluid dynamics and astrophysics) by formulating and simulating appropriate computer models.
This program will be a Java applet similar to the one you did for the
If you have not done the warmup,
Updating the position and velocity. To update the position and velocity of a Body, you will need to know its acceleration. To determine this, you first have to perform a ``force'' calculation. This requires some elementary physics, which we review now. Don't worry if your physics is a bit rusty; all of the necessary formulas are included below.
We calculate the position and velocity half a timestep out of phase (which explains the name leapfrog). Interestingly, we do not know the position and velocity at the same time step.
class Body will be similar to class Ball in many ways, except that now each body has a force associated with it. In the warmup, the velocity of a ball never changes, since there is no external force acting upon it. For a body, after each time quantum, you need to update the position and velocity according to the gravitational interactions. So, each body should have its own position, velocity, force, mass, and image. There should also be a classwide variable double G = 6.67e-11 to represent the universal gravitational constant (in the appropriate units). Remember that it is good programming practice to make all data members within a class private: make it a true ADT by only allowing access through public methods.
Body(double x, double y, double vx, double vy, double mass, Image image, Applet applet)
class Nbody is similar to MovingBall, and two version are provided to you. Nbody.java is a no frills version; NbodyDeluxe.java adds a graphical user interface. The class Nbody is the client program, and you should use exactly as is. The code below (included in Nbody.java) uses the computeForce method, along with the principle of superposition, to compute the total force acting on a particular body.
for (i = 0; i < N; i++) a[i].resetForce(); for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (i != j) a[i].computeForce(a[j]);
Try adding other features, such as merging bodies when they collide.
Or, make the simulation three-dimensional by doing calculations for x, y,
and z coordinates, then using the z coordinate to vary the sizes of
the planets. Design a planetary system with interesting behavior.