Javascript奇怪的随机行为

Kon*_*itz 9 javascript random canvas distribution

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

Ale*_*lov 3

让我回答一下,因为我对这个问题的评论很可能会被邻居迷失。

因此,通过@xiaoyi建议的修复,这张图片对我来说看起来相当随机: http: //jsfiddle.net/TvNJw。问题中最初建议的绘图例程错误地随着i增长而增加了绘制的桶宽度,而所有桶的宽度应为1。这可以通过绘制不同颜色的桶来轻松描述。