Unbias a random generator: Difference between revisions
Content deleted Content added
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
|||
Line 1,172: | Line 1,172: | ||
5: 20.05% 50.00% |
5: 20.05% 50.00% |
||
6: 17.00% 49.88%</pre> |
6: 17.00% 49.88%</pre> |
||
=={{header|jq}}== |
|||
'''Adapted from [[#Wren]]''' |
|||
{{works with|jq}} |
|||
'''Also works with gojq, the Go implementation of jq''' |
|||
In this entry, /dev/random is used as a source of entropy, |
|||
and so a suitable invocation would be: |
|||
<pre> |
|||
< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr -f unbias.jq |
|||
</pre> |
|||
'''unbias.jq''' |
|||
<syntaxhighlight lang=jq> |
|||
### Utility Functions |
|||
# Output: a PRN in range(0;$n) where $n is . |
|||
def prn: |
|||
if . == 1 then 0 |
|||
else . as $n |
|||
| (($n-1)|tostring|length) as $w |
|||
| [limit($w; inputs)] | join("") | tonumber |
|||
| if . < $n then . else ($n | prn) end |
|||
| debug |
|||
end; |
|||
def round: ((. * 100) | floor) / 100; |
|||
# input: n |
|||
# output: boolean, such that P(true) == 1/n |
|||
def biased: |
|||
prn == 1 | debug; |
|||
def unbiased: |
|||
. as $n |
|||
| {} |
|||
| until( .a != .b; {a: ($n|biased), b: ($n|biased)}) |
|||
| .a; |
|||
def task($m): |
|||
def f(x;y;z): "\(x): \(y|round)% \(z|round)%"; |
|||
range(3;7) as $n |
|||
| reduce range(0; $m) as $i ( {c1:0, c2:0}; |
|||
if ($n|biased) then .c1 += 1 else . end |
|||
| if ($n|unbiased) then .c2 += 1 else . end) |
|||
| f($n; 100 * .c1 / $m; 100 * .c2 / $m); |
|||
task(50000) |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
3: 33.61% 50.09% |
|||
4: 25.48% 50.21% |
|||
5: 20.32% 50.47% |
|||
6: 16.35% 49.72% |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |