Is there an efficient function to calculate a product?

Viewed 96

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

enter image description here

with f being a vector-valued function of a vector-valued input x. The product is taken to be a simple component-wise multiplication.

The issue here is that both the length of each x vector and the total number of result vectors (f of x) to be multiplied (N) is very large, in the order of millions. Therefore, it is impossible to generate all the results at once (it wouldn't fit in memory) and then multiply them afterwards using np.multiply.reduce or the like .

A toy example of the type of code I would like to replace is:

import numpy as np

x = np.ones(1000000)
prod = f(x)
for i in range(2, 1000000):
    prod *= f(i * np.ones(1000000))

with f a vector-valued function with the dimension of its output equal to the dimension of its input.

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

For those familiar with Wolfram Mathematica: It would be the equivalent to Product. In Mathematica, I would be able to simply write Product[f[i ConstantArray[1,1000000]],{i,1000000}].

1 Answers

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

np.multiply.reduce(v)

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

To compute the vector, just apply your function to the input:

v = f(x)

So with your example:

np.multiply.reduce(np.sin(x))

Alternative

A simpler way to phrase the same thing is np.prod:

np.prod(v)

You can also use the prod method directly on your vector:

v.prod()
Related