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.


1 Answer 1


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, 2014 at 7:57

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