如何将随机整数转换为 0 到 1 之间的浮点数 [英] How to convert random integers into float between 0 and 1

查看:89
本文介绍了如何将随机整数转换为 0 到 1 之间的浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用来自本网站的数据来获取随机数.它们作为缓冲区出现,我将其转换为二进制,然后转换为整数.我想最终将这些随机数转换为 0 到 1 之间的十进制值,就像 Math.random() 产生的那样.

I am using data from this site to get random numbers. They come in as a buffer, which I convert to binary, then into integer. I would like to finally convert those random numbers into decimal values between 0 and 1 like Math.random() produces.

例如,如果我有整数 151,我需要做什么才能使它看起来更像这个浮点 0.0151234252525372.

For example, if I have the integer 151, what do I need to do to make it look more like this float 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() 的结果将一些数学应用于初始随机数,但我不确定正确的数学是什么.

I'm not opposed to using the result of Math.random() to apply some math to the initial random number, but I'm just not sure what the right math would be.

推荐答案

您需要将该随机数除以最大值 - 这种生成的位序列的最大值为 2^length(sequence) (^ her 表示力量,**Math.pow).

You need to divide that random by max value - and max value for such generated bit sequence is 2^length(sequence) (^ her denotes power, **, Math.pow).

例如当前缓冲区为01000100",则需要计算

For example, if current buffer is "01000100", you need to calculate

68/2^8 = 68/256 = 0.265625  

这篇关于如何将随机整数转换为 0 到 1 之间的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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