javascript - Math.random()*50 + Math.random()*20 的分布与 Math.random()*70 相比如何?

标签 javascript random statistics

如何分配:

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

比较:

var randomNumber = Math.random()*70;

最佳答案

第一个不会产生更多值接近 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.

关于javascript - Math.random()*50 + Math.random()*20 的分布与 Math.random()*70 相比如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44848739/

相关文章:

r - 使用 R 将日期格式的字符串列表/向量转换为 posix 日期类

javascript - 为什么我要把 Math.floor 和 Math.random 结合起来?

javascript - 从数组中提取的列表中缺少值

python - 解释跨文档单词的 TF-IDF 分数总和

javascript - 使用 javascript 幻灯片淡入图像

Mysql - 如何在大型重复集中随机选择1行,使得每行都有 `equal`的选择机会

algorithm - 如何计算搜索图形的最小预期时间?

javascript - Meteor 服务器中的 Braintree Transaction.search

javascript - 是否可以检测三星股票浏览器

javascript - 如何在将电子邮件设为主要电子邮件之前对其进行验证(Firebase 身份验证)