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

后端 未结 4 704
南方客
南方客 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:10

    15.8.2.14 Math.random from the ES5 spec,

    Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.

    So,

    x = Math.random(); // 0 ≤ x < 1
    y = x * 5;         // 0 ≤ y < 5
    z = y + 1;         // 1 ≤ z < 6
    i = Math.floor(z); // 1 ≤ i ≤ 5, i ∈ ℤ, ℤ integers
    

    Which means

    i ∈ {1, 2, 3, 4, 5}
    

提交回复
热议问题