Random numbers and gender versus round function

Why, if I use a random number generator and a range of 0 - 9, I do not get the same uniform distribution as in combination with the gender function?

+5
source share
2 answers

Math.floor(Math.random() * 10)gives a fairly uniform distribution, but Math.round(Math.random() * 10)not.

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

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

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

, 0, 0 0,5 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 β•‘
β•šβ•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•
+24

31- int Math.floor(), " 0". ( ), , . , :

var ar=[1,2,3,4,5,6,7,8,9,0,'a','b','c','d']
console.log(ar[(Math.random() * ar.length) |0])

, , , , , , Math.floor(). Math.round() ( 1 ar.length 0 ar.length-1)

+2

All Articles