# n-body problem at shootout.alioth.debian.org

skip at pobox.com skip at pobox.com
Fri Oct 6 22:32:53 CEST 2006

```    Peter> I have noticed that in the language shootout at
Peter> shootout.alioth.debian.org the Python program for the n-body
Peter> problem is about 50% slower than the Perl program. This is an
Peter> unusual big difference. I tried to make the Python program faster
Peter> but without success. Has anybody an explanation for the
Peter> difference?  It's pure math so I expected Perl and Python to have
Peter> about the same speed.

They do have "about the same speed" (factor of 1.6x between Perl and
Python).  The Python #2 improves that to under 1.4x.

I took the original version, tweaked it slightly (probably did about the
same things as Python #2, I didn't look).  For N == 200,000 the time went
from 21.94s (user+sys) to 17.22s.  Using psyco and binding just the advance
function on my improved version improved that further to 6.48s.   I didn't
have the patience to run larger values of N.  Diff appended.

I suspect the numpy users in the crowd could do somewhat better.

Skip

% diff -u nbody.py.~1~ nbody.py
--- nbody.py.~1~        2006-10-06 15:13:31.636675000 -0500
+++ nbody.py    2006-10-06 15:24:46.048689000 -0500
@@ -5,6 +5,7 @@
# contributed by Kevin Carson

import sys
+import psyco

pi = 3.14159265358979323
solar_mass = 4 * pi * pi
@@ -14,19 +15,20 @@
pass

def advance(bodies, dt) :
-    for i in xrange(len(bodies)) :
+    nbodies = len(bodies)
+    for i in xrange(nbodies) :
b = bodies[i]

-        for j in xrange(i + 1, len(bodies)) :
+        for j in xrange(i + 1, nbodies) :
b2 = bodies[j]

dx = b.x - b2.x
dy = b.y - b2.y
dz = b.z - b2.z
-            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
+            dsqr = (dx*dx + dy*dy + dz*dz)
+            dtd3 = dt / dsqr ** 1.5
+            b_mass_x_mag = dtd3 * b.mass
+            b2_mass_x_mag = dtd3 * b2.mass

b.vx -= dx * b2_mass_x_mag
b.vy -= dy * b2_mass_x_mag
@@ -39,6 +41,7 @@
b.x += dt * b.vx
b.y += dt * b.vy
b.z += dt * b.vz

def energy(bodies) :
e = 0.0

```