n-body problem at shootout.alioth.debian.org
Paul McGuire
ptmcg at austin.rr._bogus_.com
Fri Oct 6 16:43:25 EDT 2006
"Peter Maas" <peter.maas at somewhere.com> wrote in message
news:eg6bku$59b$1 at online.de...
>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
More information about the Python-list
mailing list