Effective Java Item 47: Know and use your libraries - Flawed random integer method example

后端 未结 2 1805
悲&欢浪女
悲&欢浪女 2020-12-30 03:29

In the example Josh gives of the flawed random method that generates a positive random number with a given upper bound n, I don\'t understand the two of the fla

2条回答
  •  温柔的废话
    2020-12-30 04:17

    1) When n is a power of 2, rnd % n is equivalent to selecting a few lower bits of the original. Lower bits of numbers generated by the type of generators used by java are known to be "less random" than the higher bits. It's just the property of the formula used for generating the numbers.

    2) Imagine, that the largest possible value, returned by random() is 10, and n = 7. Now doing n % 7 maps numbers 7, 8, 9 and 10 into 0, 1, 2, 3 respectively. Therefore, if the original number is uniformly distributed, the result will be heavily biased towards the lower numbers, because they will appear twice as often as 4, 5 and 6. In this case, this does happen regardless of whether n is a power of two or not, but, if instead of 10 we chose, say, 15 (which is 2^4-1), then any n, that is a power of two would result in a uniform distribution, because there would be no "excess" numbers left at the end of the range to cause bias, because the total number of possible values would be exactly divisible by the number of possible remainders.

提交回复
热议问题