Why if I use random number generator and range 0 - 9 I don\'t get the same uniform distribution as combined it with the floor function?
I really like to trigger 31-bit int instead of Math.floor()
, by doing a binary "or 0" operation. It makes it slightly faster (stack vs heap,) seems a tad neater, and does the same thing, in a practical sense. Here is an example that gets a random element of an array:
var ar=[1,2,3,4,5,6,7,8,9,0,'a','b','c','d']
console.log(ar[(Math.random() * ar.length) |0])
This might seem like premature optimization, but as I said, I like how it looks, and it takes less typing than Math.floor()
. Using Math.round()
would require an extra step (because the spread is 1
to ar.length
not 0
to ar.length-1
)