Unbias a random generator: Difference between revisions

Add Nimrod
(Added zkl)
(Add Nimrod)
Line 928:
6: 17.20% 50.20%
</pre>
 
=={{header|Nimrod}}==
{{trans|Python}}
<lang nimrod>import math, strutils
randomize()
 
template newSeqWith(len: int, init: expr): expr =
var result {.gensym.} = newSeq[type(init)](len)
for i in 0 .. <len:
result[i] = init
result
 
proc randN(n): (proc: range[0..1]) =
result = proc(): range[0..1] =
if random(n) == 0: 1 else: 0
 
proc unbiased(biased): range[0..1] =
var (this, that) = (biased(), biased())
while this == that:
this = biased()
that = biased()
return this
 
for n in 3..6:
var biased = randN(n)
var v = newSeqWith(1_000_000, biased())
var cnt0, cnt1 = 0
for x in v:
if x == 0: inc cnt0
else: inc cnt1
echo "Biased(",n,") = count1=",cnt1,", count0=",cnt0,", percent=",
formatFloat(100 * float(cnt1)/float(cnt1+cnt0), ffDecimal, 3)
 
v = newSeqWith(1_000_000, unbiased(biased))
cnt0 = 0
cnt1 = 0
for x in v:
if x == 0: inc cnt0
else: inc cnt1
echo " Unbiased = count1=",cnt1,", count0=",cnt0,", percent=",
formatFloat(100 * float(cnt1)/float(cnt1+cnt0), ffDecimal, 3)</lang>
Output:
<pre>Biased(3) = count1=332805, count0=667195, percent=33.281
Unbiased = count1=500157, count0=499843, percent=50.016
Biased(4) = count1=249575, count0=750425, percent=24.957
Unbiased = count1=500072, count0=499928, percent=50.007
Biased(5) = count1=199537, count0=800463, percent=19.954
Unbiased = count1=499396, count0=500604, percent=49.940
Biased(6) = count1=166728, count0=833272, percent=16.673
Unbiased = count1=499712, count0=500288, percent=49.971</pre>
 
=={{header|OCaml}}==
Anonymous user