Last Updated: February 25, 2016
· ehadoux

Draw from a non-uniform probability distribution

Today's tip is about drawing a number from a non-uniform distribution by simulating it with a uniform (basic) one.

I will use integer %age probabilities but it's easily extendable to real ∈ [0,1] ones.

You need:

  1. A random number generator (say Random(0, 100) to draw ∈ [0,100[ )
  2. An array/vector containing the probability of each class you want to draw from (say P)
  3. To ensure that P sum to the max (here 100)

Now we have to cumsum P to calculate the probality interval of each class and draw a number to get the class:

int cumsum = P[0], i = 0, r;
while( cumsum <= Random(0,100) ) {
    cumsum += P[i];

At the end, i is the drawn class.

Hope this help!