Floating Point Number From Crypto.randombytes() In Javascript
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()
Solution 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 2 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.
Post a Comment for "Floating Point Number From Crypto.randombytes() In Javascript"