question on list comprehensions
dd55 at cornell.edu
Thu Oct 14 19:10:47 CEST 2004
Carlos Ribeiro wrote:
> On Thu, 14 Oct 2004 11:16:12 -0400, Darren Dale <dd55 at cornell.edu> wrote:
>> I am simulating diffraction from an array of particles. I have to
>> calculate a complex array for each particle, add up all these arrays, and
>> square the magnitude of the result. If I do a for loop, it takes about
>> 6-8 seconds for a 2000 element array added up over 250 particles. In
>> reality, I will have 2500 particles, or even 2500x2500 particles.
> Can't you just sum them inplace as you calculate every new array, for
> each particle? Something like this (pseudo code):
> result = make_empty_array()
> for particle in particles:
> result += make_complex_array(particle)
> return square(result)
> It does not grow the result array indefinitely.... so it solves your
> problem, if that's what you need/want to avoid.
You're example is what I have now, it's what I want to replace.
I am trying to make the operations general, so I can do 1x1, 1xN, and NxN
result arrays. In the case of NxN, the overhead in the for loop can be
small compared to the time required for the array operations. But for a 1x1
result array, the for loop is a huge time sink. I thought it would be nice
to get the speedup of the list comprehension, but see no way to change the
array in place. The list comprehension wants to create a new list instead.
At any rate, I found another way to frame my problem to get the speedup.
It's entirely based on linear algebra operations, no ingenious coding
involved, so I wont share the details. They are pretty mundane.
More information about the Python-list