numarray :: multiplying all the elements in 1d array

S

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.

Thanks,

regards,
Suresh
 
M

Mandus

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.
 
R

Robert Kern

Suresh said:
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.

r = multiply.reduce(a)

--
Robert Kern
(e-mail address removed)

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
 
T

Tim Hochberg

Mandus said:
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

0
0.00388960049392 0
0.042208716471 0
0.0943455103931
0
0.0146099574108
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top