28

Which of these will give an exactly 50% chance when a random value is a float between 0 and 1 (such as AS3's or JavaScript's Math.random())? I have seen both of them used in practice:

if (Math.random() > 0.5) ...
if (Math.random() >= 0.5) ...

Heads up: I'm being pedantic here, because in practice, hitting exactly 0.5 is astronomically low. However, I would still like to know where is the middle of 0 inclusive and 1 exclusive.

IQAndreas
  • 8,060
  • 8
  • 39
  • 74

2 Answers2

49

Mathematically speaking, a test which is intended to split the interval [0,1) (using [ as "inclusive" and ) as exclusive) in an exact 50-50 ratio would use a comparison like

if (Math.random() >= 0.5) ...

This is because this splits the initial interval [0,1) into two equal intervals [0,0.5) and [0.5,1).

By comparison, the test

if (Math.random() > 0.5) ...

splits the interval into [0,0.5] and (0.5,1), which have the same length, but the first is boundary-inclusive while the second is not.

Whether the boundaries are included in the same way in both tests does not matter in the limit as the precision approaches infinite, but for all finite precision, it makes a minute but measurable difference.

Suppose the precision limit is 0.000001 (decimal), then the >=0.5 test has exactly [0,0.499999] and [0.5,0.999999] and it is plain to see that adding 0.5 to the first interval (or subtracting it from the second) makes the two intervals align perfectly. On the other hand, under this precision, the >0.5 test makes the intervals [0,0.5] and [0.500001,0.999999] which are clearly unequal in favor of the numbers <=0.5. In fact, the ratio is then 500001:499999, which is obviously negligibly different from 50:50, but different all the same.

abiessu
  • 1,907
  • 1
  • 18
  • 16
  • 3
    The note about precision is a good one. Repeating a random number generation innumerable times, the "negligible" unbalanced ratio may come into play, depending on application (casino/legal/physics software, etc, though these would likely use specialized RNGs). JS uses 64-bit floats with around 15 equivalent digits of fixed-point precision, so for most uses it should be fine. – Beejor May 28 '17 at 06:19
0

Both are the same. Because you will never get Math.random() === 0.5

Please, try this test:

while (Math.random() !== 0.5) {}

This loop is endless.

D_Pavel
  • 29
  • 5
  • 2
    Note that the OP mentions Javascript, etc., but does not assume any one of these languages specifically or that the `0.5` completely fails to exist. Perhaps you could expand your answer to define the conditions and/or languages where this number does not appear in this context and what happens to the statistics in those cases, possibly even giving a hint regarding other numbers that will not exist in the given range and the sum total effect this should have on the intended 50:50 split... – abiessu Sep 05 '20 at 15:40