[英]How does the distribution of Math.random()*50 + Math.random()*20 compare to Math.random()*70?
如何分配:
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.
您可以通过计数一百万个随机值并检查总和r70s
是否等于单个随机值r70
来进行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; }
随机变量之和的密度函数是被加数的密度函数的卷积。
在这种情况下,两个被加数具有相同的密度,因此它们的卷积是分段线性函数(三角形)。 通常,对于n个均匀变量的总和,总和的密度是n-1级的分段多项式。
该总和的期望值等于期望值的总和,即50/2和20/2,等于70/2,这是Math.random()* 70的期望值。 因此,期望值相同,但是分布不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.