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

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

    Here's how I solved it in the end.

    1. Generate an integer N between 0..16, following the binomial distribution. This gives the number of '1' bits in the 16-bit partial result.
    2. Randomly generate an index into a lookup table that contains 16-bit integers containing the desired number of '1' bits.
    3. Repeat 4 times to get four 16-bit integers.
    4. Splice these four 16-bit integers together to get a 64-bit integer.

    This was partly inspired by Ondra Žižka's answer.

    The benefit is that it reduces the number of calls to Random.nextLong() to 8 calls per 64 bits of output. For comparison, rolling for each individual bit would require 64 calls. Bitwise AND/OR uses between 2 and 32 calls depending on the value of P

    Of course calculating binomial probabilities is just as expensive, so those go in another lookup table.

    It's a lot of code, but it's paying off in terms of performance.


    Update - merged this with the bitwise AND/OR solution. It now uses that method if it guesses it will be more efficient (in terms of calls to Random.next().)

提交回复
热议问题