evenly distributed random numbers

时光总嘲笑我的痴心妄想 提交于 2020-01-14 09:33:06

问题


Hey, is there way to choose evenly distributed random numbers? I used this function

Math.floor(Math.random()*2)

which returns either 1 or 0. However, I dont think it has exact 50% chance to produce either one. Better thoughts? Thank you


回答1:


If you do not believe, check:

<script type="text/javascript">
var total = 0;
var ones = 0;
for (var i = 0; i < 100000; i++, total++) {
  ones += Math.floor(Math.random()*2);
}
alert(ones/total);
</script>

This code gives me 0.49972 - very close to 50%.




回答2:


It should give you even distribution.

var a=new Array(0,0); for (i=0; i<100000; i++) a[Math.floor(Math.random() * 2)]++; alert(a);

you can try it by copy-pasting to the addressbar:

javascript:var a=new Array(0,0); for (i=0; i<100000; i++) a[Math.floor(Math.random() * 2)]++; alert(a);



回答3:


Just try it:

<script type="text/javascript">

var zero=0;
var one=0;

for (var i=0;i<1000000;i++)
{
    var num=Math.floor(Math.random()*2)
    if (num) zero++;
    if (!num) one++;
}

document.write("Zero: "+zero+"<br />");
document.write("One: "+one+"<br />");

</script>

You're looking for answers in this case which are good to within the square root of a million. i.e. you want the results coming out to be 500,000 +- 1000 if you're getting truly random numbers.




回答4:


It's close enough to 50% to the point where, if you're worried about a discrepancy (if indeed there is one), you wouldn't be using pseudo random numbers in the first place :-)

Running a loop with 10 million iterations gives me a ratio of 5,000,931 to 4,999,069 which is an error of only one in ten thousand (0.00931 percent).




回答5:


It generates 0 or 1 with equal chances.

But why didn't you use:

Math.round(Math.random())

? Do you want to be able to change to generate 0, 1, 2, ..., N ? If so keep your implementation.




回答6:


The chance for either result is exactly 50%. What makes you think that it isn't?



来源:https://stackoverflow.com/questions/5715826/evenly-distributed-random-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!