evenly distributed random numbers

2019-06-22 13:21发布

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

6条回答
倾城 Initia
2楼-- · 2019-06-22 13:59

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).

查看更多
Melony?
3楼-- · 2019-06-22 14:12

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.

查看更多
神经病院院长
4楼-- · 2019-06-22 14:14

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);
查看更多
女痞
5楼-- · 2019-06-22 14:14

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

查看更多
趁早两清
6楼-- · 2019-06-22 14:19

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.

查看更多
【Aperson】
7楼-- · 2019-06-22 14:22

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%.

查看更多
登录 后发表回答