问题
How do I convert the array of bytes returned from crypto.randomBytes into a to a floating point number? I'm writing a small replacement for Math.random()
回答1:
Suppose you have a series of bytes randomly selected with uniform distribution over [0, 256). Take seven of those bytes, say a0, a1,… a6. Calculate (((((((a6 % 32)/32 + a5)/256 + a4)/256 + a3)/256 + a2)/256 + a1)/256 + a0)/256.
Explanation: a6 % 32 denotes the residue of a6 modulo 32. This takes five bits of a6. Then division by 32 “shifts” these bits to the right of the radix point, eight new bits are added, a division by 256 “shifts” right eight bits, and so on until we have 53 bits.
This provides 253 possible results in [0, 1). It is possible to provide more since the floating-point resolution is finer as values get closer to zero, but then there are problems with uniformity and other issues.
来源:https://stackoverflow.com/questions/15753019/floating-point-number-from-crypto-randombytes-in-javascript