1

This question already has an answer here:

Let's say I have to generate random number from 1 to 100, however, the probability of each number is not 1/100, but a predefined probability.

How to generate that number? I use Ruby/Python.

marked as duplicate by Bart van Ingen Schenau, Kilian Foth, user40980, Martijn Pieters, Ampt Sep 14 '14 at 22:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

the algorithm itself is easy: create an array with all the weights' cumulative sum. After that you generate a [0-1) uniform random number and just binary search that number multiplied with the sum of the weights and the index will be the number you will need to generate.

  • 2
    +1 This is the easy way for small, discrete domains. Obviously it doesn't work for continuous (well, as continuous as you can get on a digital computer) and/or analytical distributions. Then you need an analytical solution like the inversion method. – user7043 Sep 10 '14 at 7:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.