I have a vector of probabilities $p \in \mathbb{R}^n$ which I have never seen before. I would like a single sample from the indices $(1, 2, \ldots n)$ according to the distribution defined by $p$. This could be performed in python with the following code.
import numpy as np
# Vector of probabilities
p = [0.1, 0.2, 0.3, 0.4]
# Uniform [0,1]
u = np.random.rand()
# Here's the algorithm
i = 0
while u > 0:
u -= p[i]
i += 1
# The variable `i` now has the desired distribution
print(i)
Questions:
What is the name of this algorithm?
What is an appropriate reference to cite when referring to this algorithm?
I am aware of the alias method which provides a superior way to sample from a distribution in $O(1)$, assuming you can afford a modest precomputation cost. However, since I only want to draw a single sample, this is less efficient than the algorithm described above.
u > 0.5
. But that's like finding an acceleration of the horse and buggy today... $\endgroup$ – Cliff AB Aug 16 at 21:20