Can Math.random() exactly equal .5

Viewed 134

This isn't the first time that "can Math.random() equal" has been asked.

Will JavaScript random function ever return a 0 or 1?

Is it possible for Math.random() === Math.random()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random - higher level explanation

https://hackernoon.com/how-does-javascripts-math-random-generate-random-numbers-ef0de6a20131 - lower level explanation

So; my question: can JavaScript's Math.random() ever exactly equal .5?

It fits the definition of >= 0 && < 1. But in practice, I've tried a few different approaches, last one being:

while (Math.random() != .5)

They all either time out or never exactly equal .5

Billions of attempts / several browser (firefox 60+ X64) crashes later. Is it possible? Is it browser/system dependent? Is it my lack of comprehension regarding statistical probabilities?

1 Answers

Great question! I am not a statistician, so someone with more experience feel free to hop in and correct me.

That being said, as far as I know, the answer to your question:

So; my question: can JavaScript's Math.random() ever exactly equal .5?

Is no! This answer was somewhat surprising to me, as it is somewhat counter intuitive; but I feel that this website offers a good explanation. The reason why the answer is no is because you are constrained to the range (0,1) (exclusive). This is a continuous distribution. So your question is essentially asking:

What is the probability of selecting a specific value from a continuous distribution?

The answer is 0. There are infinitely many possibilities when sampling from a continuous distribution (by definition). The probability of getting a specified value is therefore: 1/infinity, which asymptotically approaches zero.

Related