Unbias a random generator: Difference between revisions

Added 11l
(Added Wren)
(Added 11l)
Line 12:
This task is an implementation of [http://en.wikipedia.org/wiki/Randomness_extractor#Von_Neumann_extractor Von Neumann debiasing], first described in a 1951 paper.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<lang 11l>F randN(n)
‘1,0 random generator factory with 1 appearing 1/n'th of the time’
R () -> random:(@=n) == 0
 
F unbiased(biased)
‘uses a biased() generator of 1 or 0, to create an unbiased one’
V (this, that) = (biased(), biased())
L this == that
(this, that) = (biased(), biased())
R this
 
L(n) 3..6
V biased = randN(n)
V v = (0.<1000000).map(x -> @biased())
V (v1, v0) = (v.count(1), v.count(0))
print(‘Biased(#.): count1=#., count0=#., percent=#.2’.format(n, v1, v0, 100.0 * v1 / (v1 + v0)))
 
v = (0.<1000000).map(x -> unbiased(@biased))
(v1, v0) = (v.count(1), v.count(0))
print(‘ Unbiased: count1=#., count0=#., percent=#.2’.format(v1, v0, 100.0 * v1 / (v1 + v0)))</lang>
 
{{out}}
<pre>
Biased(3): count1=332946, count0=667054, percent=33.29
Unbiased: count1=499751, count0=500249, percent=49.98
Biased(4): count1=250561, count0=749439, percent=25.06
Unbiased: count1=500576, count0=499424, percent=50.06
Biased(5): count1=200056, count0=799944, percent=20.01
Unbiased: count1=499975, count0=500025, percent=50.00
Biased(6): count1=165953, count0=834047, percent=16.60
Unbiased: count1=500104, count0=499896, percent=50.01
</pre>
 
=={{header|Ada}}==
1,481

edits