gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:54:05 28 4
gpt4 key购买 nike

如何分配:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com