javascript - Random Number, Math.floor(...) vs Math.ceil(...) - Stack Overflow
[JS] So, I'm really curious about how Math.ceil works in conjunction with multiplying things from Math.random
node.js - Is there a condition where the Math.ceil function in Javascript doesn't remove decimals from the output? - Stack Overflow
Double bitwise NOT based mathematical ceiling (versus Math.ceil())
Um, please don't use this:
It's not as clear what your code is doing
It breaks at 231
It gives wrong results for negative numbers
Even if not for the last 2 points, if you know you have numbers between 0 and 231, it's rarely worth the optimization unless you're actually processing shitloads of numbers. Maybe if you're doing some ProjectEuler stuff in node
[edit] Fixing the code to account for negative numbers makes it half as fast as Math.ceil: http://jsperf.com/doublebitwisenotceil/3 (and much uglier)
Videos
as stated in MDN reference about Math.random()
Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
Since Math.random can return 0, then Math.ceil(Math.random()*10) could also return 0 and that value is out of your [1..10] range.
About your second question, see Most efficient way to create a zero filled JavaScript array?
Math.floor() is preferred here because of the range of Math.random().
For instance, Math.random() * 10 gives a range of [0, 10). Using Math.floor() you will never get to the value of 10, whereas Math.ceil() may give 0.