Code Generator for Discrete Distributions

This page generates standalone programming code that samples from a discrete distribution, or instructions to choose a random number by flipping a real coin or rolling a real die. That is, the code or instructions are designed to choose an integer in [0, n) at random where each of the n integers has a separate probability of occurring. The idea for a code generator like this came from Leydold et al. (2001). The generator supports generating JavaScript code, Ruby code, or coin-flipping instructions.

The code generator is powered by the recently presented Fast Loaded Dice Roller (Saad et al. 2020) and by the Fast Dice Roller (Lumbroso 2013). The code generator is also powered by JavaScript, at least the kind supported by modern Web browsers. Accordingly, the generator requires JavaScript (active scripting) to be enabled in the browser settings.

In the text box below, enter one of the following:

Name of generator:
Language of generated code:
The generated code will appear below. No rights are claimed to the code generated by this page (it can be used and distributed freely).

This is an open-source generator written by Peter Occil. Any copyright to this page is released to the Public Domain. In case this is not possible, this page is also licensed under Creative Commons Zero. If you have comments or issues on this generator, send them to the GitHub issues page.

About the Coin-Flipping and Die-Rolling Instructions

This generator supports generating instructions that choose a non-uniform random number by flipping a real coin or rolling a real six-sided die.


Saad, F.A., Freer C.E., et al. "The Fast Loaded Dice Roller: A Near-Optimal Exact Sampler for Discrete Probability Distributions", in _AISTATS 2020_ 108.

Leydold, et al., "An Automatic Code Generator for Nonuniform Random Variate Generation", 2001.

Lumbroso, J., "Optimal Discrete Uniform Generation from Coin Flips, and Applications", arXiv:1304.1916 [cs.DS]