evenly distributed random numbers
Hey, is there way t开发者_如何学运维o 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
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%.
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);
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.
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.
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).
The chance for either result is exactly 50%. What makes you think that it isn't?
精彩评论