Sample from a distribution

Hi all, just a quick question:
Say I have this array:

float[] probs = new float[] {0.2, 0.5, 0.3};

How do I sample from this array of probabilities to get an index? Like if say the first element with a probability of 0.2 gets selected, then return 0.

Walk the array and maintain the sum of the entries seen so far. As soon as the sum is greater than your random value, you found your index.

If you had a long array of probabilities and you were sampling it many times, you could create a new array that contains the running total, so {0.2, 0.7, 1.0} in your example. Then you just run down it looking for the first value bigger than your random value. If it was a very long array, you could binary search it to find your index.

1 Like