【问题标题】:How does the distribution of Math.random()*50 + Math.random()*20 compare to Math.random()*70?Math.random()*50 + Math.random()*20 的分布与 Math.random()*70 相比如何?
【发布时间】:2017-12-04 13:09:37
【问题描述】:

如何分配:

var randomNumber = Math.random()*50 + Math.random()*20;

比较:

var randomNumber = Math.random()*70;

【问题讨论】:

  • 我认为您会在 stat.stackexchange.com 中得到更好的答案,因为它仅取决于数学属性,而不取决于任何特定语言。试问“线性均匀分布”*A+“线性均匀分布”*B=“线性均匀分布”*(A+B)
  • 相等。 a*(b+c)=ab+ac 在 Adam Riese 之后
  • @Jonasw 那不正确。随机变量和的分布是它们的密度函数的卷积,所以一般是不同的。
  • Central Limit Theorem 适用于这种情况。两个分布之和将更接近标准分布。

标签: javascript random statistics


【解决方案1】:

第一个不会产生一个平坦的分布,在 70/2 附近有更多的值,而第二个会产生一个均匀的分布..

找出答案的简单方法是对值进行采样并绘制图表。

只是为了好玩而慢慢采样。

const ctx = canvas.getContext("2d");
const a1 = new Float64Array(70);
const a2 = new Float64Array(70);
var total = 0;
function doSamples(samples){
    for(var i = 0; i < samples; i ++){
        var n1 = Math.random() * 50 + Math.random() * 20;
        var n2 = Math.random() * 70;
        a1[n1 | 0] += 1;
        a2[n2 | 0] += 1;
    }
    var max = 0;
    for(i = 0; i < 70; i ++){
        max = Math.max(max,a1[i],a2[i]);
    }
    ctx.clearRect(0,0,canvas.width,canvas.height);
    for(i = 0; i < 70; i ++){
        var l1 = (a1[i] / max) * canvas.height;
        var l2 = (a2[i] / max) * canvas.height;
        ctx.fillStyle = "Blue";
        ctx.fillRect(i * 8,canvas.height - l1,4,l1)
        ctx.fillStyle = "Orange";
        ctx.fillRect(i * 8 + 4,canvas.height - l2,4,l2)
        
    }
    total += samples;
    count.textContent = total;
}
function doit(){
    doSamples(500);
    setTimeout(doit,100);
}
doit();
canvas {border:2px solid black;}
<canvas id="canvas" width = 560 height =  200></canvas><br>
Orange is random() * 70<br>
Blue is random() * 50 + random() * 20<br>
Graph is normalised.
<span id="count"></span> samples.

【讨论】:

    【解决方案2】:

    您可以通过计算一百万个随机值并检查总和 r70s 是否等于单个随机值 r70 来进行暴力破解。

    如您所见,分布不均。

    function countValue(key, value) {
        value = Math.floor(value);
        count[key][value] = (count[key][value] || 0) + 1;
    }
    
    var i,
        r20, r50, r70,
        count = { r20: [], r50: [], r70: [], r70s: [] };
        
    for (i = 0; i < 1e6; i++) {
        r20 = Math.random() * 20;
        r50 = Math.random() * 50;
        r70 = Math.random() * 70;
        countValue('r20', r20);
        countValue('r50', r50);
        countValue('r70', r70);
        countValue('r70s', r20 + r50);
    }
    
    console.log(count);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案3】:

      随机变量和的密度函数是被加数的密度函数的卷积。

      在这种情况下,两个和具有均匀的密度,因此它们的卷积是分段线性函数(三角形)。一般来说,对于n个均匀变量的和,和的密度是n-1次的分段多项式。

      sum的期望值等于期望值之和,即50/2和20/2,等于70/2,也就是Math.random()*70的期望值。所以期望值相同,但分布不同。

      【讨论】:

        猜你喜欢
        • 2015-09-24
        • 2019-08-24
        • 2010-10-18
        • 2011-07-31
        • 1970-01-01
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多