0

I built a simple gravity simulation shown here:

enter image description here

At first, I used a variable timestep, by calculating how much it takes for one update, and applying that to the next one - standard stuff.

However, this method reduces determinism, and results can vary from simulation to simulation - something I definitely do not want.

I figured that I should use a fixed time step (10 seconds), but then I noticed that the simulation would speed up and down in regular intervals (of around 1 second).

Why is that happening? Does it have to do anything with Python itself?


The code

The main loop:

while run:
    uni.update(10)

    for event in pygame.event.get():
        if event.type == QUIT:
            run = False

The update method:

def update (self, dt):
    self.time += dt

    for b1, b2 in combinations(self.bodies.values(), 2):
        fg = self.Fg(b1, b2)

        if b1.position.x > b2.position.x:
            b1.force.x -= fg.x
            b2.force.x += fg.x
        else:
            b1.force.x += fg.x
            b2.force.x -= fg.x


        if b1.position.y > b2.position.y:
            b1.force.y -= fg.y
            b2.force.y += fg.y
        else:
            b1.force.y += fg.y
            b2.force.y -= fg.y


    for b in self.bodies.itervalues():
        ax = b.force.x/b.m
        ay = b.force.y/b.m

        b.position.x += b.velocity.x*dt
        b.position.y += b.velocity.y*dt

        nvx = ax*dt
        nvy = ay*dt

        b.position.x += 0.5*nvx*dt
        b.position.y += 0.5*nvy*dt

        b.velocity.x += nvx
        b.velocity.y += nvy

        b.force.x = 0
        b.force.y = 0
Junuxx
  • 14,011
  • 5
  • 41
  • 71
corazza
  • 31,222
  • 37
  • 115
  • 186
  • It's very hard to answer this without knowing more about the nature of the program itself. – arshajii Oct 28 '12 at 20:15
  • Hm, it's not time-dependent at all. But here I'll post the code. – corazza Oct 28 '12 at 20:25
  • Code added, tell me if there's anything more that's needed. – corazza Oct 28 '12 at 20:27
  • 1
    Garbage collection would be one area to explore. I recommend that you enable GC debugging ( see http://docs.python.org/2/library/gc.html ). If the pauses appear to co-incide with with the collections, you can go on to profile memory use. That topic has been explored in depth here: http://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python – Ngure Nyaga Oct 28 '12 at 20:29
  • you could try [`clock.tick(fps)`](http://www.pygame.org/docs/ref/time.html) to fix your frame rate. btw, the result of the numerical method depends on time step (the smaller time step the more accurate it should be). – jfs Oct 28 '12 at 20:39

0 Answers0