console.log(Math.round(Math.random() * 5))
console.log(Math.floor(Math.random() * 6))
let x = 4
let y = 13
console.log(Math.round(Math.random() * (y - x)) + x)
console.log(Math.floor(Math.random() * (y - x + 1)) + x)
console.log('---')
function random_round(x, y) {
return Math.round(Math.random() * (y - x)) + x
}
function random_floor(x, y) {
return Math.floor(Math.random() * (y - x + 1)) + x
}
const count = 10000000
;(function () {
const staistics = new Map()
for (let i = 0; i < count; i++) {
let r = random_round(x, y)
if (staistics.has(r)) {
staistics.set(r, staistics.get(r) + 1)
} else {
staistics.set(r, 1)
}
}
for (let i = x; i <= y; i++) {
console.log(`${i} ===> ${(staistics.get(i) / count) * 100}%`)
}
})()
</script>
Math.round(Math.random() * (y - x)) + x 概率分布不好!
Math.floor(Math.random() * (y - x + 1)) + x 概率分布更好