# Is there an efficient function to calculate a product?

2994 views
5

I'm looking for a numpy function (or a function from any other package) that would efficiently evaluate

\$\$\prod_{i=1}^{N}{\overrightarrow{f}(\overrightarrow{x_i})}\$\$

with \$\overrightarrow{f}\$ being a vector valued function of a vector valued input \$\overrightarrow{x_i}\$. The product is taken to be a simple component-wise multiplication.

It would be equivalent to something like this:

``````import numpy as np

x = np.random.rand(100,10)

def f(x):
return np.sin(x)

prod = x[0].copy()
for xx in x[1:]:
prod *= f(xx)
``````

To be sure: I'm not looking for equivalent code, but for a single, highly optimized function. Is there such a thing?

Actually, something simpler may do as well. I'm fine with any function that would be equivalent to:

``````prod = f(0)
for x in range(1:100)
prod *= f(x)
``````

with `f` still a vector valued function.

For those familiar with Mathematica: It would be the equivalent to Product.

answered question

You can't just do `np.prod(map(f, x))`?

### 1 Answer

2

Numpy ufuncs all have a `reduce` method. `np.multiply` is a ufunc. So it's a one-liner:

``````np.multiply.reduce(f)
``````

Where `f` is the vector of values you compute in what is hopefully an equally efficient manner.

posted this

## Have an answer?

JD

Please login first before posting an answer.