"Peter Maas" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >I have noticed that in the language shootout at shootout.alioth.debian.org > the Python program for the n-body problem is about 50% slower than the > Perl > program. This is an unusual big difference. I tried to make the Python > program > faster but without success. Has anybody an explanation for the difference? > It's pure math so I expected Perl and Python to have about the same speed. > > Peter Maas, Aachen
The advance method is the most fertile place for optimization, since it is called approximately n(n-1)/2 times (where n=2E7). I was able to trim about 25% from the Python runtime with these changes: Change: distance = (dx**2 + dy**2 + dz**2)**0.5 b_mass_x_mag = dt * b.mass / distance**3 b2_mass_x_mag = dt * b2.mass / distance**3 to: mag = dt / (dx*dx + dy*dy + dz*dz)**1.5 b_mass_x_mag = b.mass * mag b2_mass_x_mag = b2.mass * mag And by changing the loop iteration from: for i in xrange(len(bodies)) : b = bodies[i] for j in xrange(i + 1, len(bodies)) : b2 = bodies[j] to: remainingBodies = bodies[:] for b in bodies[:-1]: del remainingBodies[0] for b2 in remainingBodies: -- Paul -- http://mail.python.org/mailman/listinfo/python-list