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

前端 未结 7 1824
隐瞒了意图╮
隐瞒了意图╮ 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:29

    Suppose the size of bit array is L. If L=1, the chance that the 1st bit is 1 will be P, and that being 0 will be 1-P. For L=2, the probability of getting a 00 is (1-P)2, a 01 or 10 is P(1-P) each and 11 is P2. Extending this logic, we can first determine the first bit by comparing a random number with P, then scale the random number such that we can again get anything between 0 to 1. A sample javascript code:

    function getRandomBitArray(maxBits,probabilityOf1) {
        var randomSeed = Math.random();
        bitArray = new Array();
        for(var currentBit=0;currentBit

    EDIT: This code does generate completely random bits. I will try to explain the algorithm better.

    Each bit string has a certain probability of occurring. Suppose a string has a probability of occurrence p; we want to choose that string if our random number falls is some interval of length p. The starting point of the interval must be fixed, but its value will not make much difference. Suppose we have chosen upto k bits correctly. Then, for the next bit, we divide the interval corresponding to this k-length bit-string into two parts of sizes in the ratio P:1-P (here P is the probability of getting a 1). We say that the next bit will be 1 if the random number is in the first part, 0 if it is in the second part. This ensure that the probabilities of strings of length k+1 also remain correct.

    Java code:

    public ArrayList getRandomBitArray(int maxBits, double probabilityOf1) {
        double randomSeed = Math.random();
        ArrayList bitArray = new ArrayList();
        for(int currentBit=0;currentBit

提交回复
热议问题