【发布时间】:2023-04-05 21:48:02
【问题描述】:
我正在使用来自this site 的数据来获取随机数。它们作为缓冲区进来,我将其转换为二进制,然后转换为整数。我想最终将这些随机数转换为 0 到 1 之间的十进制值,就像 Math.random() 产生的那样。
例如,如果我有整数151,我需要做什么才能使它看起来更像这个浮点数0.0151234252525372。
这是我的代码:
const bent = require('bent')
const getBuffer = bent('buffer')
let array = []
async function random(){
try{
let result = await getBuffer("https://qrng.anu.edu.au/wp-content/plugins/colours-plugin/get_one_binary.php")
let integer = parseInt(result.toString('utf8'), 2)
let float = parseFloat(integer) // convert to a decimal between 0 and 1 like Math.random() produces
array.push(float)
}
catch (error){return console.log(error)}
}
setInterval(()=>random().then(result => {
console.log(array)
}),50)
我不反对使用Math.random() 的结果对初始随机数应用一些数学运算,但我只是不确定正确的数学运算是什么。
【问题讨论】:
-
假设你拥有的数据是真正的二进制,你不应该把它转换成字符串,而是直接使用ArrayBuffer和TypedArray的方法来获取整数、字节等。此外,如果数字将用于信息安全目的,我发现必须将随机位转换为浮点数是不寻常的。
-
谢谢 - 我会研究 ArrayBuffer 和 TypedArray。这不是出于信息安全目的。
标签: javascript math random