javascript - Concept of Math.floor(Math.random() * 5 + 1), what is the true range and why? -


by multiplying random number (which between 0 , 1) 5, make random number between 0 , 5 (for example, 3.1841). math.floor() rounds number down whole number, , adding 1 @ end changes range between 0 , 4 between 1 , 5 (up , including 5).

the explanation above confused me... interpretation below:

--adding 5 gives range of 5 numbers --but starts 0 (like array?) --so it's technically 0 - 4 --and adding one, make 1 - 5

i new js, don't know if kind of question appropriate here, site has been great far. thank help!

from mozilla developer networks' documentation on math.random():

the math.random() function returns floating-point, pseudo-random number in range [0, 1) is, 0 (inclusive) not including 1 (exclusive).

here 2 example randomly generated numbers:

math.random() // 0.011153860716149211 math.random() // 0.9729151880834252 

because of this, when multiply our randomly generated number number, range 0 maximum of 1 lower number being multiplied (as math.floor() removes decimal places rather rounding number (that say, 0.999 becomes 0 when processed math.floor(), not 1)).

math.floor(0.011153860716149211 * 5) // 0 math.floor(0.9729151880834252 * 5)   // 4 

adding 1 offsets value you're after:

math.floor(0.011153860716149211 * 5) + 1 // 1 math.floor(0.9729151880834252 * 5) + 1   // 5 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -