A efficient binomial random number generator code in Java

后端 未结 2 1864
不知归路
不知归路 2020-12-06 20:16

The relevant question is: Algorithm to generate Poisson and binomial random numbers?

I just take her description for the Binomial random number:

相关标签:
2条回答
  • 2020-12-06 20:39

    I could imagine one way to speed it up by a constant factor (e.g. 4).

    After 4 throws you will toss a head 0,1,2,3 or 4.

    The probabilities for it are something like [0.6561, 0.2916, 0.0486, 0.0036, 0.0001].

    Now you can generate one number random number and simulate 4 original throws. If that's not clear how I can elaborate a little more.

    This way after some original pre-calculation you can speedup the process almost 4 times. The only requirement for it to be precise is that the granularity of your random generator is at least p^4.

    0 讨论(0)
  • 2020-12-06 20:48

    If you have small p values, you'll like this one better than the naive implementation you cited. It still loops, but the expected number of iterations is O(np) so it's pretty fast for small p values. If you're working with large p values, replace p with q = 1-p and subtract the return value from n. Clearly, it will be at its worst when p = q = 0.5.

    public static int getBinomial(int n, double p) {
       double log_q = Math.log(1.0 - p);
       int x = 0;
       double sum = 0;
       for(;;) {
          sum += Math.log(Math.random()) / (n - x);
          if(sum < log_q) {
             return x;
          }
          x++;
       }
    }
    

    The implementation is a variant of Luc Devroye's "Second Waiting Time Method" on page 522 of his text "Non-Uniform Random Variate Generation."

    There are faster methods based on acceptance/rejection techniques, but they are substantially more complex to implement.

    0 讨论(0)
提交回复
热议问题