Uniformly distributed random numbers

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

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

which returns either 1 or 0. However, I do not think that he has a 50% chance of producing one. Best thoughts? Thanks you

+5
source share
6 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%.

+5
source

That 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 copying it to the address bar:

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

:

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

, . .. , 500 000 + 1000, .

+3

50% , , ( ), : -)

10 5000,931 4,999,069, (0,00931 ).

+1

0 1 .

:

Math.round(Math.random())

? , , 0, 1, 2,..., N? , .

0

50%. , ?

0

All Articles