我正在使用来自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()的结果对初始随机数应用一些数学,但我只是不确定正确的数学是什么。
发布于 2020-10-22 03:52:20
你需要将这个随机数除以最大值--这样生成的位序列的最大值是2^length(sequence) (^ her表示幂,**,Math.pow)。
例如,如果当前缓冲区为"01000100",则需要计算
68/2^8 = 68/256 = 0.265625 发布于 2020-10-22 08:30:24
我使用的是数学,而不是@Mbo建议的编程。我还没有运行代码,但相当确定它会执行。或多或少地取((x的对数)/x),我在你的float变量上这样做了。
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 = (Math.log(integer)/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)https://stackoverflow.com/questions/64470083
复制相似问题