我正在使用 JavaScript 的Math.random()
函数将项目分配到存储桶中。之后,我在画布上显示桶。我希望这些项目能够均匀分布,但是(即使在多个浏览器中多次重试之后),左侧的分布似乎更加精细(接近于零)并且向右变得更加均匀(接近 1 )。见下图。
是我做错了,还是 JavaScript 的随机函数很烂?以下是用于生成此图像的代码:
<html>
<head>
<script>
window.onload = function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
var buckets = width;
var total = width*height*0.3;
var bucketList = [];
// initialized each bucket to 0 items
for(var i=0; i<buckets; ++i) {
bucketList[i] = 0;
}
// distribute all items over the buckets
for(var i=0; i<total; ++i) {
++bucketList[Math.floor(Math.random()*buckets)];
}
// draw the buckets
ctx.fillStyle = "rgb(200,0,0)";
for(var i=0; i<buckets; ++i) {
ctx.fillRect (i, height-bucketList[i], i+1, height);
}
}
</script>
</head>
<body>
<canvas id="canvas" width="1000px" height="500px"/>
</body>
</html>