javascript中的crypto.randomBytes()的浮点数 [英] floating point number from crypto.randomBytes() in javascript

查看:2455
本文介绍了javascript中的crypto.randomBytes()的浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将从crypto.randomBytes返回的字节数组转换为浮点数?我写一个小的替换Math.random()

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()

推荐答案

假设你有一系列字节随机选择均匀分布over [0,256)。取这些字节中的七个,例如 0 1 ,... a 6 。计算((((((a 6/32)/ 32 + a 5)/ 256 + a 4)/ 256 + a 3 )/ 256 + a )/ 256 + a )/ 256 + a <0> 。

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.

说明: 6 %32表示 6 模32的余数。这需要五位a 6 。然后除以32将这些位移位到小数点的右边,添加八个新位,除以256移位右8位,依此类推,直到我们有53位。

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.

这会在[0,1]中提供2个 53 种可能的结果。可以提供更多,因为浮点分辨率越精细,当值越接近零,但是有均匀性和其他问题的问题。

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.

这篇关于javascript中的crypto.randomBytes()的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆