Random numbers and floor vs round function

后端 未结 2 2034
一个人的身影
一个人的身影 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:54

    Math.floor(Math.random() * 10) gives quite uniform distribution, while Math.round(Math.random() * 10) doesn't.

    Math.floor() returns 0 for any value in the range [0, 1) (1 exclusive), 1 for any value in the range [1, 2), etc.

    So if we have equal chances of getting a number in one of these ranges, we will get an equal distribution of 0's and 1's.

    Math.round(), however, returns 0 for values under 0.5, 1 for values under 1.5, etc.

    So we actually have half the chances of getting a 0, as only values from 0 to 0.5 will round to 0.

    ╔═════════╦═════════╦═════════╗
    ║  Range  ║ floor() ║ round() ║
    ╠═════════╬═════════╬═════════╣
    ║ [0, 1)  ║ 0       ║ 0 or 1  ║
    ║ [1, 2)  ║ 1       ║ 1 or 2  ║
    ║ [2, 3)  ║ 2       ║ 2 or 3  ║
    ║ ...     ║ ...     ║ ...     ║
    ║ [9, 10) ║ 9       ║ 9 or 10 ║
    ╚═════════╩═════════╩═════════╝
    

提交回复
热议问题