0

I am seeking for some already done solution to simulate gravity interaction of n-body system, like our solar system for example, in any programming language (but preferably Javascript or C). I found this question, and it looks like exactly what I need, but, as I see, there's no interoperation between planets theyselves, only between sun and planets. I'm not so bad in JS, but really weak (more lazy) in geometry and gravity, so maybe somebody can give me an advice of how to enhance this code (or make the new one) to be able to simulate not the sun-to-planets, but full n-body gravity interaction? Or maybe you know such a software already written?

Cause as I understand, all I need is to change the code to calculate and display this:

    //...
    distanceTo: function(p2) {
        var dx = p2.position.x - this.position.x,
        dy = p2.position.y - this.position.y;
        return Math.sqrt(dx ** 2 + dy ** 2);
    },
    attraction: function(p2) {
        var dx = p2.position.x - this.position.x;
        var dy = p2.position.y - this.position.y;
        var d = Math.sqrt(dx ** 2 + dy ** 2);
        this.f = G * (this.mass * p2.mass) / (d ** 2);
        var theta = Math.atan2(dy, dx);
        var fx = Math.cos(theta) * this.f;
        var fy = Math.sin(theta) * this.f;
        this.velocity.x += fx / this.mass;
        this.velocity.y += fy / this.mass;
        this.position.x += this.velocity.x;
        this.position.y += this.velocity.y;
    }
    //...

for every single body in the system, but I'm not sure is it the right way to just iterate this code over bodies, due to such an iteration will dynamically change bodies' positions, which have been used for previous calculations within the iteration. Hope I spell it clear.

Is this possible at all? Is not this related to Three-body problem exponential computation complexity increasing? If not, can you please just direct me to right formulas and spell out simply for me, what to write and how?

Thanks!

  • You'd better use a Runge-Kutta solver rather than this crude Euler integrator. –  Jul 27 '22 at 10:36
  • For every body, sum the forces applied by the other bodies. They are proportional to δ/|δ|³ where δ is the vector between the centers. –  Jul 27 '22 at 10:38
  • see [Is it possible to make realistic n-body solar system simulation in matter of size and mass?](https://stackoverflow.com/a/28020934/2521214) and [Gravity's acceleration between two objects](https://stackoverflow.com/a/24753008/2521214) you just need to do this for every combination of objects `O(n^2)` you can do this in `(n^2)/2` iterations. Beware you should first compute the forces for all objects and only than update their positions ... – Spektre Aug 04 '22 at 08:10

0 Answers0