evenly distributed random numbers

2019-06-22 13:25发布

问题:

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?