mercredi 6 mai 2020

What are the odds of `Math.random()` producing zero? [duplicate]

According to the MDN Web Docs, regarding Math.random:

The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) . . .

So, as you can see, zero is inclusive (meaning Math.random sometimes returns zero).

Let's prove it:

// Guess how many attempts it will take for
// Math.random() to produce a zero.
let random = 1;
let min = 1;
let count = 0;
while (random > 0)
{
        random = Math.random();
        if (random < min)
        {
                min = random;
                console.log(min);
        }
        count += 1;
}
console.log(`It took Math.random() ${count} tries to produce zero.`);

It's probably better to run the code above in node or deno, because it seems that Stack Overflow's Web UI won't output one line of console.log() until the entire script has finished.

I won't spoil your curiosity by telling you how many tries it took me to produce zero.

In light of the code above, my question is this. What are the odds of Math.random() producing zero? And, my bonus question is: how does this compare with hacking a bitcoin?!




Aucun commentaire:

Enregistrer un commentaire