Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evenly distributed random numbers

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

like image 823
Clinteney Hui Avatar asked Apr 19 '11 11:04

Clinteney Hui


1 Answers

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

like image 181
Alex Netkachov Avatar answered Sep 21 '22 23:09

Alex Netkachov