[SciPy-user] Python loops too slow

alex argriffi at ncsu.edu
Wed Apr 8 09:06:51 EDT 2009


Ross Williamson wrote:
> Hi All
> 
> I'm trying to convert some IDL code into Python and am coming across the 
> incredibly slow for loop issue in python. Now I detest IDL but is there 
> any fancy way to make the following code not use for loops? Sorry if 
> this is obvious.
> 
> def make_ellgrid(ngrid, reso):
> 
>    result = zeros([ngrid, ngrid])
> 
>    for i in arange((ngrid / 2)+1):
>       for j in arange((ngrid / 2)+1):
>          result[j,i] = 2. * pi * sqrt(i ** 2. + j ** 2) / reso / (ngrid*1.0)
> 
>    for i in xrange(ngrid):
>       result[i,ngrid / 2+1:] = result[i,1:(ngrid / 2)][::-1]
>    for i in xrange(ngrid):
>       result[ngrid / 2+1:,i] = result[1:(ngrid / 2),i][::-1]
> 
>    return result
> 
> Cheers
> 
> Ross

By factoring out a constant and using hypot you might be able to speed 
up the inner loop without doing anything fancy.  Maybe something like:
c = ...
for i in ...:
   for j in ...:
     result[j,i] = hypot(j, i)
result = c * result

 From here it is easy to vectorize hypot.  To get started, you can see that:

 >>> a = np.array([[1, 1], [2, 2]])
 >>> np.hypot(a, a.T)
array([[ 1.41421356,  2.23606798],
        [ 2.23606798,  2.82842712]])

This should be like:
for i in (1,2):
   for j in (1,2):
     result[j,i] = hypot(j,i)

Now all you need to do is make the 'a' matrix where a[i,j] is equal to 
i, and I'll bet you know how to do that fast (I don't because I don't 
really know numpy).

Alex






More information about the SciPy-User mailing list