Prev: Math.random() and Math.round(Math.random()) and Math.floor(Math.random()*2)
Next: tail call optimization problem
From: Lasse Reichstein Nielsen on 1 May 2010 15:30 VK <schools_ring(a)yahoo.com> writes: > Assuming one needs to have a function returning false or true on each > call in pseudo-random order.and using JavaScript native Math.random() > method as the basis of the pseudo-randomness. Say the variants of such > function are: > > getAnswer1() { > var n = Math.round(Math.random()); > return n ? true : false; > } > > getAnswer2() { > var n = Math.floor(Math.random()*2); > return (n==2) ? true : false; As stated elsewhere, this should read return (n == 1) ? true : false; or, preferably, return n == 1; > } > > Leaving obvious practical testing by platforms aside: > > Is there are theoretical considerations that pseudo-randomness > (predictability) of either of above will be better or worse than the > other one? No, they are (obviously?) exactly identical. They map exactly the same results of Math.random() to true and false respectively. In both cases, a value in the range [0..0.5[ is mapped to false and a value in the range [0.5..1[ is mapped to true. > JavaScript Kit site claims that the second bits first: > http://www.javascriptkit.com/javatutors/randomnum.shtml > but they don't disclose the underlaying reasoning. I guess their point is that to generate an integer in the range [0..n[, Math.floor(Math.random() * n) is better, in general, than Math.round(Math.random() * (n - 1)) .... which is pretty old news (not that people still don't bungle it regularly, but it's embarrasing every time it happens). The funny thing is that for n = 2, the unevenness of using the Math.round doesn't matter, which is the case you are asking about. -- Lasse Reichstein Holst Nielsen 'Javascript frameworks is a disruptive technology' |