Uniform distribution of integers using floating point source

后端 未结 5 601
渐次进展
渐次进展 2021-01-06 00:23

The standard way to get a random integer in the range [0, n) in JavaScript - or any other language that only offers a random() function that returns a float in the range [0,

5条回答
  •  无人及你
    2021-01-06 00:47

    Assuming random() is returning a number between 0..1.

    If the result is a single precision float than thats only 23bits of entropy based on the mantissa.

    If the result is a double precision float than thats only 52bits of entropy based on the mantissa.

    So floor(random() * N) would only be uniform where N is less than 2^24 or 2^53.

    EDIT Here's some info on largest consecutive integer for floating point http://www.mathworks.com/help/matlab/ref/flintmax.html

提交回复
热议问题