How to convert random integers into float between 0 and 1

Deadly 提交于 2021-02-08 10:38:13

问题


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.

For example, if I have the integer 151, what do I need to do to make it look more like this float 0.0151234252525372.

Here is my code:

    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)

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.


回答1:


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).

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

68/2^8 = 68/256 = 0.265625  



回答2:


I am using math rather than programming as what @Mbo suggested. I haven't ran the code but fairly certain it will execute. More or less take the ((log of x)/x) and I did that on your 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)


来源:https://stackoverflow.com/questions/64470083/how-to-convert-random-integers-into-float-between-0-and-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!