TExcelTAD
Home › NumPy › ufunc Products

ufunc Products

A product multiplies the elements of an array together: the product of [2, 3, 4] is 2 × 3 × 4 = 24. NumPy's np.prod() does this, and np.cumprod() keeps the running products. Just like summation, products can work on the whole array or along an axis.

python · try it yourself
import numpy as np

dims = np.array([2, 3, 4])
print(np.prod(dims))           # volume of a 2x3x4 box

a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
print(np.prod([a, b]))         # all 8 numbers multiplied: 8! = 40320
24
40320

Product along an axis

python · try it yourself
import numpy as np

# Each row: the dimensions of one box (length, width, height) in cm
boxes = np.array([[10, 20, 5],
                  [30, 10, 10],
                  [ 8,  8,  8]])
print("volume of each box:", np.prod(boxes, axis=1))
print("product per column:", np.prod(boxes, axis=0))
volume of each box: [1000 3000  512]
product per column: [2400 1600  400]

axis=1 multiplies across each row, giving one volume per box.

Cumulative product

np.cumprod returns all the partial products. Factorials are a classic example: the running product of 1, 2, 3, … gives 1!, 2!, 3!, …

python · try it yourself
import numpy as np

print(np.cumprod(np.arange(1, 8)))         # 1!, 2!, ..., 7!

# Growth factors per year -> value of an investment after each year
growth = np.array([1.08, 0.95, 1.12, 1.03])
print((1000 * np.cumprod(growth)).round(2))
[   1    2    6   24  120  720 5040]
[1080.   1026.   1149.12 1183.59]

The second line shows why cumulative products matter in finance: returns compound, so you multiply growth factors, you don't add percentages. Over the four years above, the investment grew by about 18 %, even though one year lost 5 %.

Products and overflow

Products grow very fast, and fixed-size integers overflow silently. The default integer here (32-bit in this browser build) overflows already at 13!:

python · try it yourself
import numpy as np

n = np.arange(1, 22)
print(np.prod(n))                              # 21! overflowed: wrong!
print(np.prod(n, dtype=np.int64))              # 21! is too big even for int64
print(np.prod(n, dtype=np.float64))            # float has the range, approximately
import math
print(math.factorial(21))                      # Python ints never overflow
-1195114496
-4249290049419214848
5.109094217170944e+19
51090942171709440000

Tip: When products may get large, pass dtype=np.float64, or work with logarithms: the log of a product is the sum of the logs, so np.log(a).sum() stays small and accurate. That is how probabilities of many independent events are combined in statistics.

python · try it yourself
import numpy as np

probs = np.full(500, 0.9)                  # 500 independent events, 90 % each
print(np.prod(probs))                      # tiny, but still representable
print(np.exp(np.log(probs).sum()))         # same value through logs
print(np.prod(np.full(2000, 0.5)))         # 0.5 ** 2000 underflows to 0.0
print(np.log(np.full(2000, 0.5)).sum())    # the log is still fine
1.3220708194808237e-23
1.3220708194807995e-23
0.0
-1386.2943611198907

np.multiply.reduce and accumulate

As with summation, prod and cumprod are the reduce/accumulate methods of a ufunc, this time np.multiply:

python · try it yourself
import numpy as np

x = np.array([1, 2, 3, 4, 5])
print(np.multiply.reduce(x), np.prod(x))
print(np.multiply.accumulate(x), np.cumprod(x))
120 120
[  1   2   6  24 120] [  1   2   6  24 120]

Test yourself

What is np.prod([[1, 2], [3, 4]], axis=1)?

  1. 24
  2. [3 8]
  3. [2 12]
  4. [4 6]

What does np.cumprod([2, 3, 4]) return?

  1. 24
  2. [2 6 24]
  3. [2 5 9]
  4. [24 12 4]

Why is summing logarithms a common alternative to multiplying many probabilities?

  1. It is more readable
  2. It avoids underflow to 0.0
  3. Logs are always integers
  4. np.prod does not work on floats