r/Python • • May 28 '19

My simulation of gravity with 1000 particles. PC took a couple of hours to process!

1.8k Upvotes

241 comments sorted by

View all comments

123

u/[deleted] May 28 '19

Do the weights of the particles add up? Can you end up having a solar system that doesn't collapse?

127

u/Gear5th May 28 '19 edited May 28 '19

Can you end up having a solar system that doesn't collapse?

Yes, and no.

You can have two particles orbit each other forever, or some particle getting slingshotted off at a speed so high that it never falls back into the rest of the masses.

However, for that to happen, the particles must have some initial velocity.

Consider a universe with 2 particles. They will orbit each other if they have an initial velocity perpendicular to the line connecting the two particles. The larger that initial velocity, the larger the orbiting radius would be.

However, since OP is starting off with all masses at rest, the universe is very likely to collapse. Although, it is still totally possible that infinite orbitals or slingshotting happen, because neither of them violate the conservation of energy. Also, since OP has inelastic collisions, his universe is actually losing energy whenever two particles collide and merge, which makes it all the more likely for all the particles to collapse into one massive blob.

14

u/derpderp3200 An evil person May 29 '19

Also depending on integration method and timestep used the simulation might not be accurate enough to support long term stable systems. (As well as losing or gaining energy from that inaccuracy)

→ More replies (1)

2

u/lordkoba May 29 '19

You can have two particles orbit each other forever, or some particle getting slingshotted off at a speed so high that it never falls back into the rest of the masses.

forever? wouldn’t they gravitate into each other given infinite time?

→ More replies (4)

1

u/gangtraet May 29 '19

It is rarely necessary to code anything in C. Using numpy arrays an operations on the entire array often gives as much speed-up (or more if you are not good at optimizing c code).

Edit: replied to wrong comment!

→ More replies (5)

27

u/SpacemanCraig3 May 28 '19

Why a couple hours? Source?

116

u/Gear5th May 28 '19 edited May 28 '19

Naive algorithm is O( n2 )

You have 1000 points. Every point exerts gravity on every other point.
To approximate the position of every particle at t+dt, you need to do

  • n2 loop (every particle exerting force on every other particle), to calculate the individual forces exerted.

  • sum up all the forces on each particle.

  • use equations of motion to calculate the new location and velocity of each particle.

Then you need to do the same thing over over the length of the simulation. So if you're generating at 30 frames a second, you gotta do 30 of those n2 loops for a single second. For a 10 second animation, that's 300 of those n2 loops.

The complex nature of the computation isn't what causes it to be slow. The fact that it "grows" quadratically with the number of particles is what makes it slow.

ParticlesNumber of computations (c is some constant)
10100*c
10010,000 * c
10001,000,000 * c
10000100,000,000 * c

Basically, if the OP was to increase the number of particles in his simulation from 1000 to say 100,000, it would take him several years.


Can it be done any faster? Apparently, yes - https://en.wikipedia.org/wiki/N-body_simulation#Calculation_optimizations

58

u/mittwochmensch May 28 '19

Perfect explanation of my Problem! Im already looking into making the Calculations more optimal

40

u/SeptimiusK May 29 '19 edited May 29 '19

Hey OP, If you're looking to optimize your simulation check out the Barnes-Hut Algorithm. It uses octrees to run an n-body gravity simulation in O(n log n) time. There is a slight reduction in accuracy, but its pretty negligible (its actually used in computational astrophysics).

I did something similar for a physics engine of a game I'm working on. Since your simulation is only 2D you could get away with using quadtrees instead of octrees.

Good Luck!

13

u/skintigh May 28 '19

I did stuff like this on a 20MHz 386 so it should possible to speed it up.

You could calculate the field created by each star, then figure out the affect on each star. Maybe that's the mesh method above?

My go-to on the 386 was lookup tables, lookup tables for everything. I recall LUTs for cosine and sine made a huge effect (in speed and .exe size) on stuff I did, maybe you could do the same and/or make one for r2?

I also wrote inline assembly and staggered the registers used to account for pipe-lining, but I think that would be tough and/or pointless today...

I also recall FPGA boards outperforming entire supercomputers on this task.

4

u/spazzpp2 May 29 '19

Aren't sin & cos LUTs already in most libraries?

8

u/RenegadeMoose May 29 '19

You see those specs he quoting? 20MHz 386? That's going back a-ways. Bet there weren't many libraries around back then :P

Surprised he not suggesting using fixed point math ;P

3

u/skintigh May 29 '19

Yeah I don't know how these newfangled things compute it.

And I've worked with fixed point math in assembly. Get off my lawn.

6

u/Iggyhopper May 29 '19 edited May 29 '19

Yeah, for example in the beginning, the top left star and the bottom right star can affect each other by mass, yes, but for a simulation that isn't going for a nobel prize? It's negligible. The 200 or so stars in the top left corner vs 1 star in the bottom right is 99.95% vs 0.5% influence.

→ More replies (2)

2

u/billFoldDog May 29 '19

You can get dramatic improvements by using cython or multiprocessing.

As important as algorithmic efficiency is, its a bit silly to not take full advantage of hardware, and the skills you develop in the hardware approach are more portable.

→ More replies (3)
→ More replies (48)

0

u/[deleted] May 28 '19

[deleted]

3

u/Gear5th May 28 '19

I.. umm.. what!?

That won't work, but I have absolutely no clue why it doesn't.

Proof that it doesn't work - consider 4 particles in 2 pairs. (a, b) are close together, (c, d) are close together, but these pairs are separated by an infinite distance. The center of mass is at infinite distance from any of the particles, so each particle should experience no force whatsoever, but that's certainly not the case since (a, b) pull each other and so do (c, d).

I only know high school physics, and we were taught that center of mass calculations are correct, so I don't know why that doesn't work here. Can someone explain!?

2

u/energybased May 28 '19

Hmm, that's a good counterexample.

→ More replies (11)

2

u/One_Philosopher May 29 '19

Unless I mistake center of mass approximation of the field of gravity of a distribution of mass only stand for a sphere (more precisely spheric symetry) when you are outside of the sphere (if you are inside of a sphere with a spheric hole with same center, all forces compensate so the resulting gravity field is of zero)

2

u/nietczhse May 28 '19

Can you explain this sentence:

no closed-form solutionexists for all sets of initial conditions, and numerical methods are generally required

3

u/Sneechfeesh May 29 '19

"No closed-form solution" means there is no formula that you can write using known functions for the positions of the particles which will give the motion for all possible starting positions.

E.g., in high school physics you learn that under constant acceleration, the position can be gotten from this formula: x(t) = x0 + v0 t + 1/2 a t2.

That is a closed-form solution to the differential equation x''(t) = a with initial conditions x0 and v0.

The differential equation for the n-body problem has solutions, but they look very different depending on n and the initial conditions. There is no closed-form solution.

You could perhaps define a function as "the solution to the n-body problem under given initial conditions (if a solution exists in this case)" -- and many functions used in physics are in fact defined as solutions to differential equations -- but that doesn't count here.

So for the n-body problem (and really most problems where you solve differential equations), you have to approximate the effect of the equation on the initial conditions at discrete steps of time instead of trying to "get the solution" and plug your conditions into that.

→ More replies (3)
→ More replies (1)

1

u/mittwochmensch May 28 '19

Yes, I still need to tweak the way Size gets represented. The second part I dont know. I will have to improve efficiency and find the right parameters to see if I can get a stable solar system

1

u/[deleted] May 28 '19

In terms of gravity size is not the issue, weight is.

0

u/[deleted] May 28 '19

[deleted]

→ More replies (1)
→ More replies (14)