Random number with Probabilities

前端 未结 12 2250
醉梦人生
醉梦人生 2020-11-27 02:56

I am wondering what would be the best way (e.g. in Java) to generate random numbers within a particular range where each number has a certain probability to occur or not?

12条回答
  •  面向向阳花
    2020-11-27 03:24

    If you have performance issue instead of searching all the n values O(n)

    you could perform binary search which costs O(log n)

    Random r=new Random();      
    double[] weights=new double[]{0.1,0.1+0.2,0.1+0.2+0.5};
    // end of init
    double random=r.nextDouble();
    // next perform the binary search in weights array
    

    you only need to access log2(weights.length) in average if you have a lot of weights elements.

提交回复
热议问题