为什么这个random()分布看起来不对称? [英] Why does this random() distribution look asymmetric?

查看:245
本文介绍了为什么这个random()分布看起来不对称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑: Google Chrome 36

This is using Google Chrome 36

我是用html5画布乱码,生成随机分布在多维数据集中的点并将其投影到2D画布上。令人惊讶的是,结果看起来并不完全对称,我怀疑Javascript的Math.random()让我失望。

I was messing around with html5 canvas, generating points randomly distributed inside a cube and projecting that onto a 2D canvas. Surprisingly, the results don't look very symmetric at all, and I suspect that Javascript's Math.random() is letting me down.

任何人都可以告诉我为什么发生?

Can anyone tell me why this is happening? Is it possible to make it actually look random, without making it slower?

var ctx = canvas.getContext('2d');

for (var i = 0; i < 10000000; i++) {
    var x = Math.random()*2-1, y = Math.random()*2-1, z = 2+Math.random()*2-1;
    x = (.5 + .5*x/z) * canvas.width;
    y = (.5 + .5*y/z) * canvas.height;
    ctx.fillRect(Math.floor(x), Math.floor(y), 1, 1);
}

http://jsfiddle.net/y10tvj26/ (需要一段时间加载)

http://jsfiddle.net/y10tvj26/ (Takes a while to load)

推荐答案

Chrome浏览器具有记录的问题,随后调用Math .random()相关。在您的算法中,相关值将倾向于落在画布上的一条线上。对Math.random()的额外调用打破了相关性。我还没有看到其他浏览器受到影响的报告。

Chrome has a documented issue that subsequent calls to Math.random() are correlated. In your algorithm, correlated values will tend to fall on a line on the canvas. An extra call to Math.random() breaks that correlation. I haven't seen reports that other browsers are affected.

只需调用 Math.random()

var ctx = canvas.getContext('2d');

var ctx = canvas.getContext('2d');

function r() {
    Math.random();
    return Math.random();
}
for (var i=0; i<10000000; i++) {
    var x = r()*2-1, y = r()*2-1, z = 2+r()*2-1;
    x = (.5 + .5*(x/z)) * canvas.width;
    y = (.5 + .5*(y/z)) * canvas.height;
    ctx.fillRect(x, y, 1, 1);
}

更新于: http://jsfiddle.net/y10tvj26/5/

这篇关于为什么这个random()分布看起来不对称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆