numarray :: multiplying all the elements in 1d array
Tim Hochberg
tim.hochberg at ieee.org
Wed Dec 21 09:26:17 EST 2005
Mandus wrote:
> Tue, 20 Dec 2005 19:32:13 +0530 skrev Suresh Jeevanandam:
>
>>Hi all,
>> Lets say I have an array:
>> from numarray import *
>> a = array([ 6, 7, 8, 9, 10, 11, 12])
>>
>> I want to multiply out all the elements and get the result.
>>
>> r = 1.0
>> for i in a:
>> r = r*i
>>
>> Is there any faster, efficient way of doing this.
>
>
> You can use multiply.reduce(a) (multiply is a function imported from
> numarray).
>
> With regular python you can also do:
>
> from operator import mul
> reduce(mul,a)
>
> This work even when 'a' is a plain python list.
Actually, they'll both work with a plain python list. Multiply.reduce is
much faster (see below) when operating on arrays, but somewhat slower
when operating on lists. I'd guess from the overhead of converting the
list to an array.
-tim
>>> a = na.arange(100000)
>>> l = range(100000)
>>> t0 = time.clock(); na.multiply.reduce(a); print time.clock() - t0
0
0.00388960049392
>>> t0 = time.clock(); na.multiply.reduce(l); print time.clock() - t0
0
0.042208716471
>>> t0 = time.clock(); reduce(mul, a); print time.clock() - t0
0
0.0943455103931
>>> t0 = time.clock(); reduce(mul, l); print time.clock() - t0
0
0.0146099574108
More information about the Python-list
mailing list