0

I'd like to sum a function f over unordered pairs (n,m) with n and m distinct, where n,m range from -N to N.

The function depends on a sequence of floats stored in a dictionary, indexed from -N to N. It looks something like:

def f(n,m):
    return dict[n]*dict[m]*np.sin(c*(n-m)) / (n-m)

Naively, I'd write:

indices = [ (n,m) for n in range(-N,N+1) for m in range(-N,N+1) if m>n ]
sum([f(n,m) for (n,m) in indices])

Is there a way to vectorize this with numpy and make it more efficient? I'm using Python 3, in case it matters.

daunpunk
  • 1
  • 1
  • What do you mean when you say the pairs are unordered? It looks like your function indeed depends on the order of `n` and `m`. – BrenBarn Oct 15 '15 at 18:28
  • 1
    Add sample input, output and explain how the code works through to get to the output? – Divakar Oct 15 '15 at 18:42
  • Also, if `n` is a scalar, `dict[n]` would throw an error, right? – Divakar Oct 15 '15 at 19:16
  • @BrenBarn: sin is an odd function, so the sign change from flipping n,m inside the sin cancels the sign change from flipping n,m in (n-m). – daunpunk Oct 15 '15 at 19:17
  • @Divakar: Sorry, I don't understand why there'd be an error. The keys to a dictionary can be integers. – daunpunk Oct 15 '15 at 19:19
  • @daunpunk: Ah, I didn't read carefully enough. Anyway, you could look at [this question](http://stackoverflow.com/questions/16992713/translate-every-element-in-numpy-array-according-to-key). If you can vectorize the dict lookups the rest should be easy. – BrenBarn Oct 15 '15 at 19:21
  • I think adding a sample input would make it more clear. – Divakar Oct 15 '15 at 19:21

0 Answers0