Unbias a random generator: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: changed the title when using the default of 1,000. -- ~~~~)
(→‎{{header|Ruby}}: added comments to code.)
Line 1,279: Line 1,279:


def unbiased(bias)
def unbiased(bias)
a, b = rand_n(bias), rand_n(bias) until a != b
a, b = rand_n(bias), rand_n(bias) until a != b #loop until a and b are 0,1 or 1,0
a
a
end
end
Line 1,288: Line 1,288:


(3..6).each do |bias|
(3..6).each do |bias|
counter = Hash.new(0)
counter = Hash.new(0) # counter will respond with 0 when key is not known
runs.times do
runs.times do
counter[:biased] += 1 if rand_n(bias) == 1
counter[:biased] += 1 if rand_n(bias) == 1 #the first time, counter has no key for : biased, so it will respond 0
counter[:unbiased] += 1 if unbiased(bias) == 1
counter[:unbiased] += 1 if unbiased(bias) == 1
end
end