Unbias a random generator: Difference between revisions
Content added Content deleted
(added Fortran) |
(added Lua example) |
||
Line 181: | Line 181: | ||
5: 20.05% 50.00% |
5: 20.05% 50.00% |
||
6: 17.00% 49.88%</pre> |
6: 17.00% 49.88%</pre> |
||
=={{header|Lua}}== |
|||
<lang lua> |
|||
local function randN(n) |
|||
if n < 3 or n > 6 then error "Invalid bias" end |
|||
local chance = 1/n |
|||
return function() |
|||
if math.random() < chance then return 1 else return 0 end |
|||
end |
|||
end |
|||
local function unbiased(n) |
|||
local biased = randN (n) |
|||
return function() |
|||
local a, b = biased(), biased() |
|||
while a==b do |
|||
a, b = biased(), biased() |
|||
end |
|||
return a |
|||
end |
|||
end |
|||
local function demonstrate (samples) |
|||
for n = 3, 6 do |
|||
biased = randN(n) |
|||
unbias = unbiased(n) |
|||
local bcounts = {[0]=0,[1]=0} |
|||
local ucounts = {[0]=0,[1]=0} |
|||
for i=1, samples do |
|||
local bnum = biased() |
|||
local unum = unbias() |
|||
bcounts[bnum] = bcounts[bnum]+1 |
|||
ucounts[unum] = ucounts[unum]+1 |
|||
end |
|||
print(string.format("N = %d",n), |
|||
"# 0", "# 1", |
|||
"% 0", "% 1") |
|||
print("biased", bcounts[0], bcounts[1], |
|||
bcounts[0] / samples * 100, |
|||
bcounts[1] / samples * 100) |
|||
print("unbias", ucounts[0], ucounts[1], |
|||
ucounts[0] / samples * 100, |
|||
ucounts[1] / samples * 100) |
|||
end |
|||
end |
|||
demonstrate(100000) |
|||
</lang> |
|||
Output: |
|||
<pre> |
|||
N = 3 # 0 # 1 % 0 % 1 |
|||
biased 66832 33168 66.832 33.168 |
|||
unbias 50207 49793 50.207 49.793 |
|||
N = 4 # 0 # 1 % 0 % 1 |
|||
biased 75098 24902 75.098 24.902 |
|||
unbias 49872 50128 49.872 50.128 |
|||
N = 5 # 0 # 1 % 0 % 1 |
|||
biased 80142 19858 80.142 19.858 |
|||
unbias 50049 49951 50.049 49.951 |
|||
N = 6 # 0 # 1 % 0 % 1 |
|||
biased 83407 16593 83.407 16.593 |
|||
unbias 49820 50180 49.82 50.18 |
|||
</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |