【问题标题】:How to convert random integers into float between 0 and 1如何将随机整数转换为 0 到 1 之间的浮点数
【发布时间】: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


【解决方案1】:

您需要将该随机数除以最大值 - 这样生成的位序列的最大值为 2^length(sequence)(^ 她表示功率,**Math.pow)。

例如,如果当前缓冲区为“01000100”,则需要计算

68/2^8 = 68/256 = 0.265625  

【讨论】:

  • 这似乎不起作用。出于我的目的,该数字始终需要介于 0 和 1 之间。这是一个示例输出:buffer=<Buffer 31 31 31 31 31 30 30 30>binary=11111000integer=248,结果:float=24.8,我使用的是let float = integer/2^8
  • 2^8 表示 2 的 8 次方;不幸的是,javascript 将 ^ 解释为按位异或。您想使用 2**8 而不是适当的运算符(在现代浏览器中),或者您可以更明确地使用 Math.pow
  • @SamMason 啊,不错!谢谢!
【解决方案2】:

我使用数学而不是 @Mbo 建议的编程。我还没有运行代码,但相当肯定它会执行。或多或少地取 ((log of x)/x),我在你的 float var 上做了。

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)

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 2011-07-07
    • 2012-12-17
    • 2016-04-05
    • 2019-07-19
    • 2016-11-29
    • 2012-12-18
    相关资源
    最近更新 更多