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

后端 未结 4 694
南方客
南方客 2021-01-05 15:39

By multiplying the random number (which is between 0 and 1) by 5, we make it a random number between 0 and 5 (for example, 3.1841). Math.floor() rounds this number down to a

4条回答
  •  感情败类
    2021-01-05 16:26

    From the Mozilla Developer Networks' documentation on Math.random():

    The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive).

    Here are two example randomly generated numbers:

    Math.random() // 0.011153860716149211
    Math.random() // 0.9729151880834252
    

    Because of this, when we multiply our randomly generated number by another number, it will range from 0 to a maximum of 1 lower than the number being multiplied by (as Math.floor() simply removes the decimal places rather than rounding the number (that is to say, 0.999 becomes 0 when processed with Math.floor(), not 1)).

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

    Adding one simply offsets this to the value you're after:

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

提交回复
热议问题