Random numbers and floor vs round function

后端 未结 2 2014
一个人的身影
一个人的身影 2021-02-06 06:27

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?

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 06:31

    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)

提交回复
热议问题