[Numpy-discussion] Square All Elements Of A Matrix

David M. Cooke cookedm at physics.mcmaster.ca
Wed May 11 13:30:25 EDT 2005


andrea_gavana at tin.it writes:

> Hello NG,
>
>     in one script, I generated a matrix "dx" which has a (200000, 10) shape.
> Well, everything is working fine (matrix multiplication, sum, exponentiation
> etc...), but I'm having problems in squaring all elements of this matrix.
>
> Suppose I have:
>
> import Numeric
> import random
>
> dx = Numeric.ones((200000,10), Numeric.Float0, savespace=1)
> dx[:,:] = random.random()

It's faster to do

import RandomArray

dx = RandomArray.random((200000,10)).astype(Numeric.Float0)
dx.savespace(1)

(it won't use the same RNG as random, though)

> td1 = dx*2.0   ---> This takes about 0.2 seconds
> td2 = dx**2.0 ---> This takes about 6 seconds
>
> Why this difference? And why it is so slow the exponentiation? I have tried
> the same operation in Matlab and it was almost instantaneous. I don't want
> to stick with Matlab, noting the great job the Numeric developers
> have done.

Hmm, I don't see this, with either 23.8 or 24.0b2. What version of
Numeric are you using, and on what platform?

dx**2 uses the C 'pow' function on each element (so using 2 or 2.0
here doesn't make a difference), so may be your platform pow() is
slow.

dx*dx should be faster (it takes 80% of the time that dx**2 does on my
machine).

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke                      http://arbutus.physics.mcmaster.ca/dmc/
|cookedm at physics.mcmaster.ca




More information about the NumPy-Discussion mailing list