问题
I have a random_rand() function which produces a random number between 0 and RANDOM_RAND_MAX. RANDOM_RAND_MAX is defined to be 65535.
I would like to use the middle bits from the result of random_rand() instead of lowest-order bits so that I can make the randomiztion better.
Could you please show me a quick way to do this.
Thanks
回答1:
That's naughty.
Linear congruential generators work in such a way that the "most random" part comprises the lower order bits. A very famous IBM implementation of rand
a couple of decades ago swapped the highest and lowest bits round after a drawing as a final flourish - this was found to completely ruin the generator!
So keep things simple. Generate your random number and extract the least significant bits using the %
operator or a bitwise &
: although this introduces statistical bias, the effects are no worse than the generator itself.
Whatever you end up doing, always run some statistical checks on your generator to make sure it has adequate statistical properties. At the time of writing, the generation scheme that seems to be the "best one" is the Mersenne Twister.
(If you really want the middle bits, then use a mixture of the bitwise right shift operator >>
and &
.)
回答2:
result = (random_rand() >> 4) & 0xff
This shifts the whole result right by four bits (destroying the first four bit) and then logically-AND's the result with binary 0000000011111111
so only the next 8 bits are taken.
But when you need to resort to such dirty hacks to improve the quality of your pseudorandom number generator, you should rather consider to use a better PRNG instead. The mersenne twister, for example, is a very good tradeoff between performance and quality.
来源:https://stackoverflow.com/questions/40846909/how-to-return-middle-bits-from-random-number-generator