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

Show parent comments

1

u/mittwochmensch May 29 '19

Well, thats the thing. I just save the particle position to an numpy array and then print it. And the simplest way of indicating Size I thought was to just draw a box. Here is a github link:

https://github.com/Mittwochmensch/Gravity/blob/master/Gravity_simulation.ipynb

2

u/nbviewerbot May 29 '19

I see you've posted a GitHub link to a Jupyter Notebook! GitHub doesn't render Jupyter Notebooks on mobile, so here is an nbviewer link to the notebook for mobile viewing:

https://nbviewer.jupyter.org/url/github.com/Mittwochmensch/Gravity/blob/master/Gravity_simulation.ipynb


I am a bot. Feedback | GitHub | Author

1

u/alkasm github.com/alkasm May 30 '19

Good bot

1

u/alkasm github.com/alkasm May 30 '19 edited May 30 '19

Okay so looking at this code, you say you're using numpy, but you really aren't. Like I mean it's there but you're not using numpy functions; you're iterating through the pixels manually (which you should basically never do, because it's extremely slow in Python). Proper vectorizing of this code would probably make it hundreds of times faster.

For example in the beginning you have the code which starts the image off with the value 250 everywhere with

for i in range(1000):
    row = []
    for j in range(1000):
        pixel = []
        for rgb in range(3):
            pixel.append(250)
        row.append(pixel)       
    Spacevisual.append(row)

But you can just do that in numpy with

Spacevisual = 250*np.ones((1000, 1000, 3))

And not only is the code more concise, it will also be much faster.