floating point number from crypto.randomBytes() in javascript

懵懂的女人 提交于 2019-12-23 16:41:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!