Monday, June 3, 2024
183
rated 0 times [  185] [ 2]  / answers: 1 / hits: 26001  / 11 Years ago, sun, february 2, 2014, 12:00:00

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.


More From » actionscript-3

 Answers
12

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.


[#72792] Friday, January 31, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;