NumPy Multinomial Distribution
A multinomial draw distributes a fixed number of trials across several outcome categories. Each row of counts should sum to the same trial total.
How it works
The probability vector describes mutually exclusive outcomes whose probabilities satisfy the generator’s requirements. In this toy example, ten fictional observations fall into three labelled collection categories. Keep the labels in the same order as the vector and returned counts. The counts in one draw need not match the probability proportions exactly, particularly for small totals.
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 multinomial.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
probabilities = np.array([0.2, 0.3, 0.5])
draws = np.random.default_rng(41).multinomial(n=10, pvals=probabilities, size=4)
print(draws.shape)
print(draws.sum(axis=1).tolist())
print(bool((draws >= 0).all()))
Expected result
(4, 3) [10, 10, 10, 10] True
Each of four simulated experiments has three category counts and preserves its total of ten. This invariant is more meaningful than expecting an exact [2, 3, 5] split in every row.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.