Dshiz
Dshiz

Reputation: 3341

How to convert random integers into float between 0 and 1

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.

Upvotes: 0

Views: 1636

Answers (2)

MBo
MBo

Reputation: 80325

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  

Upvotes: 2

Brandon Raeder
Brandon Raeder

Reputation: 94

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)

Upvotes: 0

Related Questions