Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 enter image description here.

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>
like image 226
Konstantin Weitz Avatar asked May 22 '12 10:05

Konstantin Weitz


1 Answers

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.

like image 111
Alexander Pavlov Avatar answered Oct 02 '22 21:10

Alexander Pavlov