2012-05-22 20 views
9

Estoy usando la función Math.random() de JavaScript para distribuir artículos en intervalos. Después, muestro los cubos en un lienzo. Esperaría que los artículos se distribuyan uniformemente, pero (incluso después de múltiples intentos en múltiples navegadores), parece que la distribución es mucho más fina a la izquierda (más cerca de cero) y se vuelve más uniforme hacia la derecha (más cerca de 1) Consulte la siguiente imagen enter image description here.Javascript comportamiento aleatorio extraño

¿Lo estoy haciendo mal o la función aleatoria de JavaScript es una mierda? A continuación se muestra el código que se utiliza para generar esta imagen:

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

'ctx.fillRect (i, height-bucketList [i], i + 1, height);' debe ser 'ctx.fillRect (i, height-bucketList [i], 1, height);' – xiaoyi

+1

+1 por hacer esta pregunta a la perfección. Está redactado con claridad, el código es completo, fácil de seguir y limpio, y la imagen muestra exactamente lo que está sucediendo. La pregunta en sí es interesante y relevante. ¡Gracias! –

+0

@AdamLiss trazó los números incorrectamente ... – xiaoyi

Respuesta

3

permítame responder con una respuesta, ya que mi comentario sobre la cuestión tiene una gran oportunidad para perderse entre sus vecinos.

Por lo tanto, con la solución sugerida por @xiaoyi en su lugar, la imagen parece bastante aleatoria para mí: http://jsfiddle.net/TvNJw. La rutina de trazado sugerida originalmente en la pregunta aumenta incorrectamente el ancho del canasto pintado a medida que crece i, mientras que todos los cangilones deben tener el ancho de 1. Esto se puede representar fácilmente trazando cubos con diferentes colores.