Generate a random binary number with a variable proportion of '1' bits

前端 未结 7 1825
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 16:55

I need a function to generate random integers. (assume Java long type for now, but this will be extended to BigInteger or BitSet later

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 17:20

    If you're looking to apply some distribution where with probability P you get a 1 and with probability 1-P you get a 0 at any particular bit your best bet is simply to generate each bit independently with probability P of being a 1 (that sounds like a recursive definition, I know).

    Here's a solution, I'll walk through it below:

    public class MyRandomBitGenerator
    {
    
        Random pgen = new Random();
    
        // assumed p is well conditioned (0 < p < 1)
        public boolean nextBitIsOne(double p){
            return pgen.nextDouble() < p ? true : false;
        }
    
        // assumed p is well conditioned (0 < p < 1)
        public long nextLong(double p){
            long nxt = 0;
            for(int i = 0; i < 64; i++){
               if(nextBitIsOne(p)){
                   nxt += 1 << i;
               }
            }
            return nxt;
        }
    
    }
    

    Basically, we first determine how to generate a value of 1 with probability P: pgen.nextDouble() generates a number between 0 and 1 with uniform probability, by asking if it's less than p we're sampling this distribution such that we expect to see p 1s as we call this function infinitely.

提交回复
热议问题