本文介绍了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)。取这些字节中的七个,例如,,... a 。计算((((((a 6/32)/ 32 + a 5)/ 256 + a 4)/ 256 + a )/ 256 + a )/ 256 + a )/ 256 + a 。

Suppose you have a series of bytes randomly selected with uniform distribution over [0, 256). Take seven of those bytes, say a, a,… a. Calculate (((((((a % 32)/32 + a)/256 + a)/256 + a)/256 + a)/256 + a)/256 + a)/256.

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

Explanation: a % 32 denotes the residue of a modulo 32. This takes five bits of a. 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个种可能的结果。可以提供更多,因为浮点分辨率越精细,当值越接近零,但是有均匀性和其他问题的问题。

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.

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

10-23 18:24