A simple discrete random sampler in C++
Sampling from a finite set of weighted outcomes is a small task that appears surprisingly often in simulation, stochastic modelling, and Monte Carlo methods. In this post we build a compact C++ function for drawing from a discrete distribution, then compare its behaviour with std::discrete_distribution. We will briefly discuss how to sample a discrete random variable in theory and practice, before constructing our own algorithm and comparing its performance to the std::discrete_distribution in the C++ standard library. Many hand-coded discrete samplers have been proposed, but often these are unnecessarily clunky and, consequently, slow. ...