Unbias a random generator: Difference between revisions
Content added Content deleted
(→{{header|Ruby}}: Added Ruby sample) |
|||
Line 1,275: | Line 1,275: | ||
</pre> |
</pre> |
||
=={{header|Ruby}}== |
|||
<lang ruby>def rand_n(bias) |
|||
rand(bias) <=> 0 |
|||
end |
|||
def unbiased(bias) |
|||
a, b = rand_n(bias), rand_n(bias) until a != b |
|||
a |
|||
end |
|||
runs = 1_000_000 |
|||
keys = %i(bias biased unbiased) #use [:bias,:biased,:unbiased] in Ruby < 2.0 |
|||
puts keys.join("\t") |
|||
(3..6).each do |bias| |
|||
counter = Hash.new(0) |
|||
runs.times do |
|||
counter[:biased] += 1 if rand_n(bias) == 1 |
|||
counter[:unbiased] += 1 if unbiased(bias) == 1 |
|||
end |
|||
counter[:bias] = bias |
|||
puts counter.values_at(*keys).join("\t") |
|||
end</lang> |
|||
{{output}} |
|||
<pre> |
|||
bias biased unbiased |
|||
3 666180 499845 |
|||
4 749748 499773 |
|||
5 799898 500192 |
|||
6 833180 500740 |
|||
</pre> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
<lang seed7>$ include "seed7_05.s7i"; |
<lang seed7>$ include "seed7_05.s7i"; |