0

I have to do a summation over 2 indices in a 2D plane and in each point in space I have to get a value of a function.

The simplest way and the only way I know how to do it was with 4 for loops. It works well but it is extremely slow. Do you have any sugestions how to do it faster.

Note that "size" defines the step I am using and is the size of my sistem in arbitrary units and "n_0" is a list of lists and is an input parameter which is also dependent on the coordinates x in y.

for x in range(size):
    for y in range(size):
        for x_ in range(size):
            for y_ in range(size):
                if x == x_ and y == y_:
                    pass
                else:
                    value = n_0[x][y] * N / math.sqrt((x - x_)**2 + (y - y_)**2)
                    print(value)

EDIT: I dont know why this was marked a duplicate because my problem is not being more concise with my syntax. My problem is that the code no matter what the syntax is is O(n^4) and I need to reduce this.

  • Just to confirm, you are disregarding any coordinates _outside_ your coordinate system with the coordinate `in range(size)` checks? Also, what is `N` defined as? – Jonathon Ogden Jul 26 '16 at 10:20
  • It may not help much, but should consider math.hypot instead of squaring and computing square root manually. – guidot Jul 26 '16 at 10:20
  • How large is the typical `size`? I would suggest using numpy as it allows to perform the calculations faster, but it would require to store vectors in memory – Nick Slavsky Jul 26 '16 at 10:20
  • I am disregarding all the outside coordinates yes. Only within my border area. The size parameter is currently at 100 and it still takes about a minute. And N is the number of particles inside the area. Only a number. – Matic Pečovnik Jul 26 '16 at 10:24
  • Additionally to what was said, I would suggest that you replace the power with multiplication as it is always faster. Here is why: http://stackoverflow.com/questions/1019740/speed-of-calculating-powers-in-python – Nick Slavsky Jul 26 '16 at 11:04

1 Answers1

0

For Python 2.x xrange is faster than range and normally (2.x and 3.x) it is even faster to do

i=start
while i<stop:
    #do something
    i+=1

instead of

for i in range(start,stop):
    #do something

because a for-loop does more complicated stuff.

Also it is (a bit) faster to do

import a
c=[]

def f():
    a_b_local=a.b
    c_local=c
    #some loop with a_b_local and c_local

than

import a
c=[]

def f():
    #some loop with a.b and c

because name lookups take some time

janbrohl
  • 2,626
  • 1
  • 17
  • 15