Unbias a random generator: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Phix}}: syntax coloured, rounded to nearest whole percent) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 16:
{{trans|Python}}
<
‘1,0 random generator factory with 1 appearing 1/n'th of the time’
R () -> random:(@=n) == 0
Line 35:
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)))</
{{out}}
Line 50:
=={{header|Ada}}==
<
procedure Bias_Unbias is
Line 100:
Ada.Text_IO.New_Line;
end loop;
end Bias_Unbias;</
Output:<pre> I Biased% UnBiased%
3 32.87 49.80
Line 110:
=={{header|Aime}}==
{{trans|C}}
<
biased(integer bias)
{
Line 148:
0;
}</
Output:<pre>bias 3: 33.51% vs 50.27%
bias 4: 24.97% vs 49.99%
Line 156:
=={{header|AutoHotkey}}==
{{output?}}
<
Random, q, 0, 4
return q=4
Line 170:
MsgBox % "Unbiased probability of a 1 occurring: " Errorlevel/1000
StringReplace, junk, t, 1, , UseErrorLevel
MsgBox % "biased probability of a 1 occurring: " Errorlevel/1000</
Line 176:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
function randN (n)
if int(rand * n) + 1 <> 1 then return 0 else return 1
Line 206:
next n
end
</syntaxhighlight>
{{out}}
<pre>
Line 226:
=={{header|BBC BASIC}}==
<
biased% = 0
unbiased% = 0
Line 245:
= A%
DEF FNrandN(N%) = -(RND(N%) = 1)</
Output:
<pre>
Line 255:
=={{header|C}}==
<
#include <stdlib.h>
Line 286:
return 0;
}</
output
<pre>bias 3: 33.090% vs 49.710%
Line 295:
=={{header|C++}}==
{{trans|C#}}
<
#include <random>
Line 348:
}
return 0;
}</
{{out}}
<pre>(N = 3)
Line 384:
=={{header|C sharp}}==
<
namespace Unbias
Line 442:
}
}
}</
'''Sample Output'''
Line 461:
=={{header|Clojure}}==
<
(if (< (rand 2) (/ n)) 0 1))
Line 477:
[4 0.87684 0.5023]
[5 0.90122 0.49728]
[6 0.91526 0.5])</
=={{header|CoffeeScript}}==
<
biased_rand_function = (n) ->
# return a function that returns 0/1 with
Line 510:
stats "biased", f_biased
stats "unbiased", f_unbiased
</syntaxhighlight>
output
<pre>
Line 533:
=={{header|Common Lisp}}==
<
(defun unbiased (n)
Line 543:
(let ((u (loop repeat 10000 collect (unbiased n)))
(b (loop repeat 10000 collect (biased n))))
(format t "~a: unbiased ~d biased ~d~%" n (count 0 u) (count 0 b))))</
output
<pre>3: unbiased 4992 biased 3361
Line 551:
=={{header|D}}==
<
enum biased = (in int n) /*nothrow*/ => uniform01 < (1.0 / n);
Line 567:
M.iota.map!(_=> n.biased).sum * 100.0 / M,
M.iota.map!(_=> n.unbiased).sum * 100.0 / M);
}</
{{out}}
<pre>3: 33.441% 49.964%
Line 577:
{{trans|C#}}
ELENA 4.x :
<
extension op : IntNumber
Line 621:
unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000)
}
}</
{{out}}
<pre>
Line 639:
=={{header|Elixir}}==
<
def randN(n) do
if :rand.uniform(n) == 1, do: 1, else: 0
Line 655:
ys = for _ <- 1..m, do: Random.unbiased(n)
IO.puts "#{n} #{Enum.sum(xs) / m} #{Enum.sum(ys) / m}"
end</
{{out}}
Line 667:
=={{header|ERRE}}==
<
FUNCTION RANDN(N)
Line 697:
END FOR
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>N = 3 : biased = 32.66 , unbiased = 49.14
Line 706:
=={{header|Euphoria}}==
<
return rand(N) = 1
end function
Line 730:
end for
printf(1, "%d: %5.2f%% %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n})
end for</
Output:
Line 740:
=={{header|F_Sharp|F#}}==
<
let random = Random()
Line 761:
printfn "%d: %5.2f%% %5.2f%%"
b (100. * float !cb / float n) (100. * float !cu / float n)
0</
{{out}}
<pre>3: 33.26% 49.97%
Line 769:
=={{header|Factor}}==
<
IN: rosetta-code.unbias
Line 787:
] each ;
MAIN: main</
{{out}}
<pre>
Line 798:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 846:
end function
end program</
Output:
<pre>3: 33.337% 49.971%
Line 857:
=={{header|FreeBASIC}}==
{{trans|PureBasic}}
<
Function randN (n As Ubyte) As Ubyte
If Int(Rnd * n) + 1 <> 1 Then Return 0 Else Return 1
Line 894:
Next n
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 922:
=={{header|GAP}}==
<
local v, rand;
v := [1 .. n - 1]*0;
Line 959:
# [ 4, 249851, 500663 ],
# [ 5, 200532, 500448 ],
# [ 6, 166746, 499859 ] ]</
=={{header|Go}}==
<
import (
Line 1,001:
u[1], u[0], float64(u[1])*100/samples)
}
}</
Output:
<pre>
Line 1,017:
=={{header|Haskell}}==
The first task:
<
import Control.Monad
import Text.Printf
randN :: MonadRandom m => Int -> m Int
randN n = fromList [(0, fromIntegral n-1), (1, 1)]</
Examples of use:
Line 1,031:
The second task. Returns the unbiased generator for any given random generator.
<
unbiased g = do x <- g
y <- g
if x /= y then return y else unbiased g</
Examples of use:
Line 1,043:
The third task:
<
where
showCounts b = do
Line 1,050:
printf "n = %d biased: %d%% unbiased: %d%%\n" b r1 r2
counts g = (`div` 100) . length . filter (== 1) <$> replicateM 10000 g</
Output:
Line 1,064:
This solution works in both languages. Both <tt>randN</tt> and
<tt>unbiased</tt> are generators in the Icon/Unicon sense.
<
iters := \A[1] | 10000
write("ratios of 0 to 1 from ",iters," trials:")
Line 1,093:
procedure randN(n)
repeat suspend if 1 = ?n then 1 else 0
end</
and a sample run:
<pre>->ubrn 100000
Line 1,108:
=={{header|J}}==
<
unbiased=: i.@# { ::$: 2 | 0 3 -.~ _2 #.\ 4&* randN@# ]</
Example use:
<
1 0 0 0 1 0 0 0 0 0
unbiased 10#6
1 0 0 1 0 0 1 0 1 1</
Some example counts (these are counts of the number of 1s which appear in a test involving 100 random numbers):
<
30
+/randN 100#4
Line 1,135:
49
+/unbiased 100#6
47</
Note that these results are random. For example, a re-run of <code>+/randN 100#5</code> gave 25 as its result, and a re-run of <code>+/unbiased 100#5</code> gave 52 as its result.
=={{header|Java}}==
<
public static boolean biased(int n) {
return Math.random() < 1.0 / n;
Line 1,166:
}
}
}</
Output:
<pre>3: 33,11% 50,23%
Line 1,174:
=={{header|Julia}}==
<
randN(N) = () -> rand(1:N) == 1 ? 1 : 0
Line 1,195:
v1, v0 = count(v .== 1), count(v .== 0)
@printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "unbiased", v1, v0, 100 * v1 / nrep)
end</
{{out}}
Line 1,210:
=={{header|Kotlin}}==
{{trans|Java}}
<
fun biased(n: Int) = Math.random() < 1.0 / n
Line 1,237:
println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m))
}
}</
Sample output:
Line 1,248:
=={{header|Lua}}==
<
local function randN(n)
return function()
Line 1,291:
demonstrate(100000)
</syntaxhighlight>
Output:
Line 1,310:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
unbiased[bias_, n_] := DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]]
count = 1000000;
Line 1,316:
Table[{n, Total[rand[n, count]]/count // N,
Total[#]/Length[#] &@unbiased[n, count] // N}, {n, 3, 6}],
TableHeadings -> {None, {n, "biased", "unbiased"}}]</
{{out}}
<pre>n biased unbiased
Line 1,326:
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref symbols binary
Line 1,361:
end n
return
</syntaxhighlight>
'''Output:'''
<pre>
Line 1,372:
=={{header|Nim}}==
{{trans|Python}}
<
type randProc = proc: range[0..1]
Line 1,401:
for x in v:
if x == 0: inc cnt0 else: inc cnt1
echo &"Unbiased → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"</
{{out}}
Line 1,415:
=={{header|OCaml}}==
<
if Random.int n = 0 then 1 else 0
Line 1,434:
Printf.printf "%d: %5.2f%% %5.2f%%\n"
b (100.0 *. float !cb /. float n) (100.0 *. float !cu /. float n)
done</
Output:
Line 1,445:
=={{header|PARI/GP}}==
GP's random number generation is high-quality, using Brent's [http://maths.anu.edu.au/~brent/random.html XORGEN]. Thus this program is slow: the required 400,000 unbiased numbers generated through this bias/unbias scheme take nearly a second. This requires about two million calls to <code>random</code>, which in turn generate a total of about three million calls to the underlying random number generator through the rejection strategy. The overall efficiency of the scheme is 0.8% for 32-bit and 0.4% for 64-bit...
<
unbiased(N)={
my(a,b);
Line 1,454:
)
};
for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n))))</
Output:
Line 1,463:
=={{header|Perl}}==
<
my $n = shift;
return int(rand($n) / ($n - 1));
Line 1,483:
100 * sqrt($fixed[0] * $fixed[1]) / ($fixed[0] + $fixed[1])**1.5);
}</
Output:
<pre>Bias 3: 6684 3316, 66.84+-0.471% fixed: 2188 2228, 49.5471+-0.752%
Line 1,491:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">randN</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">)</span>
Line 1,516:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"%d: biased:%.0f%% unbiased:%.0f%%\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,(</span><span style="color: #000000;">cb</span><span style="color: #0000FF;">/</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,(</span><span style="color: #000000;">cu</span><span style="color: #0000FF;">/</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<small>''(Rounded to the nearest whole percent, of course)''</small>
Line 1,527:
=={{header|PicoLisp}}==
<
(if (= 1 (rand 1 N)) 1 0) )
Line 1,536:
(setq A (randN N))
(setq B (randN N)) ) )
A ) )</
Test:
<
(tab (2 1 7 2 7 2)
N ":"
Line 1,548:
(let S 0 (do 10000 (inc 'S (unbiased N))))
2 )
"%" ) )</
Output:
<pre> 3: 33.21 % 50.48 %
Line 1,556:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
test: procedure options (main); /* 20 Nov. 2012 */
Line 1,586:
end test;
</syntaxhighlight>
Results:
<pre>
Line 1,598:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
function randN ( [int]$N )
{
Line 1,614:
return $X
}
</syntaxhighlight>
Note: The [pscustomobject] type accelerator, used to simplify making the test output look pretty, requires version 3.0 or higher.
<syntaxhighlight lang="powershell">
$Tests = 1000
ForEach ( $N in 3..6 )
Line 1,632:
"Unbiased Ones out of $Test" = $Unbiased }
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,644:
=={{header|PureBasic}}==
<
If Random(n) <> 1
ProcedureReturn 0
Line 1,678:
output + #tab$ + " ratio=" + StrF(u_count(1) / #count * 100, 2) + "%" + #LF$
Next
MessageRequester("Biased and Unbiased random number results", output)</
Sample output:
<pre>---------------------------
Line 1,697:
=={{header|Python}}==
<
import random
Line 1,724:
v = [unbiased(biased) for x in range(1000000)]
v1, v0 = v.count(1), v.count(0)
print ( " Unbiased = %r" % (Stats(v1, v0, 100. * v1/(v1 + v0)), ) )</
'''Sample output'''
Line 1,739:
=={{header|Quackery}}==
<
[ random 0 = ] is randN ( n --> n )
Line 1,765:
[ dup cr
showbias cr
showunbias cr ] </
{{out}}
Line 1,784:
=={{header|R}}==
<
unbiased = function(f)
Line 1,794:
N = N,
biased = mean(replicate(samples, randN(N))),
unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))</
Sample output:
Line 1,805:
=={{header|Racket}}==
<
#lang racket
;; Using boolean #t/#f instead of 1/0
Line 1,819:
(printf "Count: ~a => Biased: ~a%; Unbiased: ~a%.\n"
n (try% biased) (try% (unbiased biased))))
</syntaxhighlight>
{{out}}
<pre>
Line 1,832:
{{trans|Perl}}
{{works with|Rakudo|2020.08.1}}
<syntaxhighlight lang="raku"
return ( $n.rand / ($n - 1) ).Int;
}
Line 1,851:
printf "N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
$n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;
}</
Output:<pre>N=3 randN: [676, 324], 32.4% unbiased: [517, 483], 48.3%
Line 1,859:
=={{header|REXX}}==
<
parse arg # R seed . /*obtain optional arguments from the CL*/
if #=='' | #=="," then #=1000 /*#: the number of SAMPLES to be used.*/
Line 1,877:
pct: return ctr( format(arg(1) / # * 100, , 2)'%' ) /*2 decimal digits.*/
randN: parse arg z; return random(1, z)==z /*ret 1 if rand==Z.*/
unbiased: do until x\==randN(N); x=randN(N); end; return x /* " unbiased RAND*/</
{{out|output|text= when using the default inputs:}}
<pre>
Line 1,928:
=={{header|Ring}}==
<
for n = 3 to 6
biased = 0
Line 1,948:
m = (random(m) = 1)
return m
</syntaxhighlight>
Output:
<pre>
Line 1,958:
=={{header|Ruby}}==
<
rand(bias) == 0 ? 1 : 0
end
Line 1,979:
counter[:bias] = bias
puts counter.values_at(*keys).join("\t")
end</
{{output}}
<pre>
Line 1,990:
=={{header|Rust}}==
<
extern crate rand;
Line 2,028:
);
}
}</
{{output}}
<pre>
Line 2,039:
=={{header|Scala}}==
<
def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop }
Line 2,051:
"%d: %2.2f%% %2.2f%%".format(i, 100.0*c1/m, 100.0*c2/m)
}</
{{output}}
<pre>3: 33.09% 49.79%
Line 2,059:
=={{header|Seed7}}==
<
include "float.s7i";
Line 2,092:
" " <& flt(100 * sumUnbiased) / flt(tests) digits 3 lpad 6);
end for;
end func;</
Output:
Line 2,104:
=={{header|Sidef}}==
{{trans|Raku}}
<
n.rand / (n-1) -> int
}
Line 2,125:
printf("N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
n, [raw, fixed].map {|a| (a.dump, a[1] * 100 / iterations) }...)
}</
{{out}}
<pre>
Line 2,135:
=={{header|Tcl}}==
<
proc randN n {expr {rand()*$n < 1}}
Line 2,157:
puts [format "unbiased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \
[expr {100.*$c(1)/$i}]]
}</
Sample output:
<pre>
Line 2,172:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Dim random As New Random()
Line 2,216:
End Sub
End Module</
{{out}}
<pre>(N = 3): # of 0 # of 1 % of 0 % of 1
Line 2,234:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<
import "/fmt" for Fmt
Line 2,259:
}
Fmt.print(f, n, 100 * c1 / m, 100 * c2 / m)
}</
{{out}}
Line 2,271:
=={{header|zkl}}==
<
fcn unbiased(randN){ while((a:=randN())==randN()){} a }</
<
foreach N in ([3..6]){
"%d: biased: %3.2f%%, unbiased: %3.2f%%".fmt(N,
Line 2,279:
(0).reduce(Z,'wrap(s,_){ s+unbiased(randN.fp(N)) },0.0)/Z*100)
.println();
}</
{{out}}
<pre>
|