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:
- A random number generator (say
Random(0, 100)
to draw ∈ [0,100[ ) - An array/vector containing the probability of each class you want to draw from (say
P
) - 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) ) {
i++;
cumsum += P[i];
}
At the end, i
is the drawn class.
Hope this help!
Written by Emmanuel Hadoux
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Mathematics
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#