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 .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>
'ctx.fillRect (i, height-bucketList [i], i + 1, height);' debe ser 'ctx.fillRect (i, height-bucketList [i], 1, height);' – xiaoyi
+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! –
@AdamLiss trazó los números incorrectamente ... – xiaoyi