简体   繁体   中英

Javascript weird random behavior

I'm using JavaScript's Math.random() function to distribute items over buckets. Afterwards, I display the buckets in a canvas. I would expect the items to be distributed evenly, but (even after multiple retries in multiple browsers), it seems like the distribution is much more fine grained on the left (closer to zero) and becomes more uniform towards the right (closer to 1). See the following image 在此输入图像描述 .

Am I doing it wrong, or does JavaScript's random function suck? Below is the code that was used to generate this image:

<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>

Let me respond with an answer, since my comment on the question has a great chance to be lost among its neighbors.

So, with the fix suggested by @xiaoyi in place, the picture looks quite random to me: http://jsfiddle.net/TvNJw . The plotting routine originally suggested in the question wrongly increases the painted bucket width as i grows, while all buckets should have the width of 1 . This can easily be depicted by plotting buckets with different colors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM