NumPy Cumulative Sums and Products
cumsum accumulates additions, while cumprod accumulates multiplications. The two operations represent different kinds of change and need different units.
How it works
A running collection total is additive. A sequence of scale factors is multiplicative and can represent successive proportional adjustments in a toy calculation. prod combines all factors into one value; cumprod preserves the intermediate results. Integer products can overflow quickly, and floating products can underflow or accumulate error. Use a representation and interpretation suited to the range rather than assuming a cumulative API guarantees accuracy.
Run the code
Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.
For local work, use a separate virtual environment and run python cumulative-products.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.
Example
import numpy as np
litres = np.array([12, 18, 24], dtype=np.int64)
factors = np.array([2, 3, 2], dtype=np.int64)
print(np.cumsum(litres).tolist())
print(np.cumprod(factors).tolist())
print(int(np.prod(factors)))
Expected result
[12, 30, 54] [2, 6, 12] 12
The final running total equals the sum, while the final cumulative product equals the product. Intermediate values retain the order of the inputs, which matters when explaining when each change occurred.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.