Anonymous user
Unbias a random generator: Difference between revisions
no edit summary
No edit summary |
No edit summary |
||
Line 605:
5: 20.05% 50.00%
6: 17.00% 49.88%</pre>
=={{header|Liberty BASIC}}==
<lang lb>
for N =3 to 6 ' bias as defined
tests =1E5 ' number of tests to do
print " Biased bit-string, '1' chosen on average once out of "; N; " times . . . "
countZeros =0: countOnes =0
for j =1 to tests
b =randN( N)
if b =1 then countOnes =countOnes +1 else countZeros =countZeros +1
next j
print " "; countZeros; " zeros & "; countOnes; " ones. Ratio ="; countOnes /tests
print " Unbiased bit-string . . . "
countZeros =0: countOnes =0
for j =1 to tests
b =unBiased( N)
if b =1 then countOnes =countOnes +1 else countZeros =countZeros +1
next j
print " "; countZeros; " zeros & "; countOnes; " ones. Ratio ="; countOnes /tests
print
next N
print " DONE."
end ' _____________________________________________________
function randN( n)
if rnd( 1) <( 1 /n) then randN =1 else randN =0
end function
function unBiased( n)
do
n1 =randN( n)
n2 =randN( n)
loop until n1 <>n2
unBiased =n1
end function
</lang>
Output:
Biased bit-string, '1' chosen once out of 3 times . . .
664236 zeros & 335764 ones. Ratio =0.335764
Unbiased bit-string . . .
500349 zeros & 499651 ones. Ratio =0.499651
Biased bit-string, '1' chosen once out of 4 times . . .
748122 zeros & 251878 ones. Ratio =0.251878
Unbiased bit-string . . .
499728 zeros & 500272 ones. Ratio =0.500272
Biased bit-string, '1' chosen once out of 5 times . . .
798517 zeros & 201483 ones. Ratio =0.201483
Unbiased bit-string . . .
500044 zeros & 499956 ones. Ratio =0.499956
Biased bit-string, '1' chosen once out of 6 times . . .
832096 zeros & 167904 ones. Ratio =0.167904
Unbiased bit-string . . .
500407 zeros & 499593 ones. Ratio =0.499593
=={{header|Lua}}==
|