Unbias a random generator: Difference between revisions

m
(Unbias a random generator en FreeBASIC)
 
(14 intermediate revisions by 10 users not shown)
Line 1:
{{task}}Given a weighted one -bit generator of random numbers where the probability of a one occuringoccurring, <math>P_1</math>, is not the same as <math>P_0</math>, the probability of a zero occuringoccurring, the probability of the occurrence of a one followed by a zero is <math>P_1</math> × <math>P_0</math>, assuming independence. This is the same as the probability of a zero followed by a one: <math>P_0</math> × <math>P_1</math>.
 
 
Line 16:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F randN(n)
‘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)))</langsyntaxhighlight>
 
{{out}}
Line 50:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; with Ada.Numerics.Discrete_Random;
 
procedure Bias_Unbias is
Line 100:
Ada.Text_IO.New_Line;
end loop;
end Bias_Unbias;</langsyntaxhighlight>
Output:<pre> I Biased% UnBiased%
3 32.87 49.80
Line 110:
=={{header|Aime}}==
{{trans|C}}
<langsyntaxhighlight lang="aime">integer
biased(integer bias)
{
Line 148:
 
0;
}</langsyntaxhighlight>
Output:<pre>bias 3: 33.51% vs 50.27%
bias 4: 24.97% vs 49.99%
Line 156:
=={{header|AutoHotkey}}==
{{output?}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">Biased(){
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</langsyntaxhighlight>
 
 
Line 176:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
function randN (n)
if int(rand * n) + 1 <> 1 then return 0 else return 1
Line 206:
next n
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 226:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> FOR N% = 3 TO 6
biased% = 0
unbiased% = 0
Line 245:
= A%
DEF FNrandN(N%) = -(RND(N%) = 1)</langsyntaxhighlight>
Output:
<pre>
Line 255:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
Line 286:
 
return 0;
}</langsyntaxhighlight>
output
<pre>bias 3: 33.090% vs 49.710%
Line 295:
=={{header|C++}}==
{{trans|C#}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <random>
 
Line 348:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>(N = 3)
Line 384:
=={{header|C sharp}}==
 
<langsyntaxhighlight lang="csharp">using System;
 
namespace Unbias
Line 442:
}
}
}</langsyntaxhighlight>
 
'''Sample Output'''
Line 461:
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(defn biased [n]
(if (< (rand 2) (/ n)) 0 1))
 
Line 477:
[4 0.87684 0.5023]
[5 0.90122 0.49728]
[6 0.91526 0.5])</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
biased_rand_function = (n) ->
# return a function that returns 0/1 with
Line 510:
stats "biased", f_biased
stats "unbiased", f_unbiased
</syntaxhighlight>
</lang>
output
<pre>
Line 533:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun biased (n) (if (zerop (random n)) 0 1))
 
(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))))</langsyntaxhighlight>
output
<pre>3: unbiased 4992 biased 3361
Line 551:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.range, std.functional;
 
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);
}</langsyntaxhighlight>
{{out}}
<pre>3: 33.441% 49.964%
Line 573:
5: 19.958% 49.987%
6: 16.660% 49.890%</pre>
 
=={{header|EasyLang}}==
{{trans|Java}}
<syntaxhighlight>
func biased n .
return if randomf < 1 / n
.
func unbiased n .
repeat
a = biased n
b = biased n
until a <> b
.
return a
.
m = 50000
for n = 3 to 6
c1 = 0
c2 = 0
for i to m
c1 += biased n
c2 += unbiased n
.
print n & ": " & 100 * c1 / m & " " & 100 * c2 / m
.
</syntaxhighlight>
{{out}}
<pre>
3: 33.10 50.14
4: 25.03 50.14
5: 19.81 50.04
6: 16.75 49.83
</pre>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
extension op : IntNumber
Line 601 ⟶ 634:
public program()
{
for(int n := 3,; n <= 6,; n += 1)
{
int biasedZero := 0;
Line 608 ⟶ 641:
int unbiasedOne := 0;
for(int i := 0,; i < 100000,; i += 1)
{
if(n.randN()) { biasedOne += 1 } else { biasedZero += 1 };
Line 621 ⟶ 654:
unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 639 ⟶ 672:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Random do
def randN(n) do
if :rand.uniform(n) == 1, do: 1, else: 0
Line 655 ⟶ 688:
ys = for _ <- 1..m, do: Random.unbiased(n)
IO.puts "#{n} #{Enum.sum(xs) / m} #{Enum.sum(ys) / m}"
end</langsyntaxhighlight>
 
{{out}}
Line 667 ⟶ 700:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM UNBIAS
 
FUNCTION RANDN(N)
Line 697 ⟶ 730:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>N = 3 : biased = 32.66 , unbiased = 49.14
Line 706 ⟶ 739:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function randN(integer N)
return rand(N) = 1
end function
Line 730 ⟶ 763:
end for
printf(1, "%d: %5.2f%% %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n})
end for</langsyntaxhighlight>
 
Output:
Line 740 ⟶ 773:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let random = Random()
Line 761 ⟶ 794:
printfn "%d: %5.2f%% %5.2f%%"
b (100. * float !cb / float n) (100. * float !cu / float n)
0</langsyntaxhighlight>
{{out}}
<pre>3: 33.26% 49.97%
Line 769 ⟶ 802:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel math math.ranges random sequences ;
IN: rosetta-code.unbias
 
Line 787 ⟶ 820:
] each ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 798 ⟶ 831:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Bias_Unbias
implicit none
 
Line 846 ⟶ 879:
end function
 
end program</langsyntaxhighlight>
Output:
<pre>3: 33.337% 49.971%
Line 857 ⟶ 890:
=={{header|FreeBASIC}}==
{{trans|PureBasic}}
<langsyntaxhighlight lang="freebasic">
Function randN (n As Ubyte) As Ubyte
If Int(Rnd * n) + 1 <> 1 Then Return 0 Else Return 1
Line 894 ⟶ 927:
Next n
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 913 ⟶ 946:
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Unbias_a_random_generator}}
 
'''Solution'''
 
[[File:Fōrmulæ - Unbias a random generator 01.png]]
 
[[File:Fōrmulæ - Unbias a random generator 02.png]]
 
[[File:Fōrmulæ - Unbias a random generator 03.png]]
 
'''Test cases'''
 
[[File:Fōrmulæ - Unbias a random generator 04.png]]
 
[[File:Fōrmulæ - Unbias a random generator 05.png]]
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">RandNGen := function(n)
local v, rand;
v := [1 .. n - 1]*0;
Line 952 ⟶ 1,002:
# [ 4, 249851, 500663 ],
# [ 5, 200532, 500448 ],
# [ 6, 166746, 499859 ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 994 ⟶ 1,044:
u[1], u[0], float64(u[1])*100/samples)
}
}</langsyntaxhighlight>
Output:
<pre>
Line 1,010 ⟶ 1,060:
=={{header|Haskell}}==
The first task:
<langsyntaxhighlight lang="haskell">import Control.Monad.Random
import Control.Monad
import Text.Printf
 
randN :: MonadRandom m => Int -> m Int
randN n = fromList [(0, fromIntegral n-1), (1, 1)]</langsyntaxhighlight>
 
Examples of use:
Line 1,024 ⟶ 1,074:
 
The second task. Returns the unbiased generator for any given random generator.
<langsyntaxhighlight Haskelllang="haskell">unbiased :: (MonadRandom m, Eq x) => m x -> m x
unbiased g = do x <- g
y <- g
if x /= y then return y else unbiased g</langsyntaxhighlight>
 
Examples of use:
Line 1,036 ⟶ 1,086:
 
The third task:
<langsyntaxhighlight Haskelllang="haskell">main = forM_ [3..6] showCounts
where
showCounts b = do
Line 1,043 ⟶ 1,093:
printf "n = %d biased: %d%% unbiased: %d%%\n" b r1 r2
counts g = (`div` 100) . length . filter (== 1) <$> replicateM 10000 g</langsyntaxhighlight>
 
Output:
Line 1,057 ⟶ 1,107:
This solution works in both languages. Both <tt>randN</tt> and
<tt>unbiased</tt> are generators in the Icon/Unicon sense.
<langsyntaxhighlight lang="unicon">procedure main(A)
iters := \A[1] | 10000
write("ratios of 0 to 1 from ",iters," trials:")
Line 1,086 ⟶ 1,136:
procedure randN(n)
repeat suspend if 1 = ?n then 1 else 0
end</langsyntaxhighlight>
and a sample run:
<pre>->ubrn 100000
Line 1,101 ⟶ 1,151:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">randN=: 0 = ?
unbiased=: i.@# { ::$: 2 | 0 3 -.~ _2 #.\ 4&* randN@# ]</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> randN 10#6
1 0 0 0 1 0 0 0 0 0
unbiased 10#6
1 0 0 1 0 0 1 0 1 1</langsyntaxhighlight>
 
Some example counts (these are counts of the number of 1s which appear in a test involving 100 random numbers):
 
<langsyntaxhighlight lang="j"> +/randN 100#3
30
+/randN 100#4
Line 1,128 ⟶ 1,178:
49
+/unbiased 100#6
47</langsyntaxhighlight>
 
Note that these results are randomarbitrary. 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}}==
<langsyntaxhighlight lang="java">public class Bias {
public static boolean biased(int n) {
return Math.random() < 1.0 / n;
Line 1,159 ⟶ 1,209:
}
}
}</langsyntaxhighlight>
Output:
<pre>3: 33,11% 50,23%
Line 1,165 ⟶ 1,215:
5: 20.05% 50.00%
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
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}}==
<langsyntaxhighlight lang="julia">using Printf
 
randN(N) = () -> rand(1:N) == 1 ? 1 : 0
Line 1,188 ⟶ 1,293:
v1, v0 = count(v .== 1), count(v .== 0)
@printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "unbiased", v1, v0, 100 * v1 / nrep)
end</langsyntaxhighlight>
 
{{out}}
Line 1,203 ⟶ 1,308:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun biased(n: Int) = Math.random() < 1.0 / n
Line 1,230 ⟶ 1,335:
println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m))
}
}</langsyntaxhighlight>
 
Sample output:
Line 1,241 ⟶ 1,346:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
local function randN(n)
return function()
Line 1,284 ⟶ 1,389:
 
demonstrate(100000)
</syntaxhighlight>
</lang>
 
Output:
Line 1,302 ⟶ 1,407:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">rand[bias_, n_] := 1 - Unitize@RandomInteger[bias - 1, n]
unbiased[bias_, n_] := DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]]
 
count = 1000000;
unbiased[bias_, n_] :=
DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]]</lang>
 
<pre>count = 1000000;
TableForm[
Table[{n, Total[rand[n, count]]/count // N,
Total[#]/Length[#] &@unbiased[n, count] // N}, {n, 3, 6}],
TableHeadings -> {None, {n, "biased", "unbiased"}}]</syntaxhighlight>
{{out}}
 
<pre>n biased unbiased
3 0.33312 0.500074
4 0.24932 0.499883
5 0.1998 0.498421
6 0.16620 0.49805</pre>
 
</pre>
 
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,359 ⟶ 1,459:
end n
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,370 ⟶ 1,470:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import random, sequtils, strformat
 
type randProc = proc: range[0..1]
Line 1,399 ⟶ 1,499:
for x in v:
if x == 0: inc cnt0 else: inc cnt1
echo &"Unbiased → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"</langsyntaxhighlight>
 
{{out}}
Line 1,413 ⟶ 1,513:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let randN n =
if Random.int n = 0 then 1 else 0
 
Line 1,432 ⟶ 1,532:
Printf.printf "%d: %5.2f%% %5.2f%%\n"
b (100.0 *. float !cb /. float n) (100.0 *. float !cu /. float n)
done</langsyntaxhighlight>
 
Output:
Line 1,443 ⟶ 1,543:
=={{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...
<langsyntaxhighlight lang="parigp">randN(N)=!random(N);
unbiased(N)={
my(a,b);
Line 1,452 ⟶ 1,552:
)
};
for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n))))</langsyntaxhighlight>
 
Output:
Line 1,461 ⟶ 1,561:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub randn {
my $n = shift;
return int(rand($n) / ($n - 1));
Line 1,481 ⟶ 1,581:
100 * sqrt($fixed[0] * $fixed[1]) / ($fixed[0] + $fixed[1])**1.5);
 
}</langsyntaxhighlight>
Output:
<pre>Bias 3: 6684 3316, 66.84+-0.471% fixed: 2188 2228, 49.5471+-0.752%
Line 1,489 ⟶ 1,589:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
Copy of [[Unbias_a_random_generator#Euphoria|Euphoria]]
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang Phix>function randN(integer N)
<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>
return rand(N) = 1
<span style="color: #008080;">return</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function unbiased(integer N)
<span style="color: #008080;">function</span> <span style="color: #000000;">unbiased</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">)</span>
integer a
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
while 1 do
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">randN</span><span style="color: #0000FF;">(</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span>
a = randN(N)
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">randN</span><span style="color: #0000FF;">(</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
if a!=randN(N) then
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end function
<span style="color: #008080;">constant</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100000</span>
constant n = 10000
<span style="color: #008080;">for</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #000000;">6</span> <span style="color: #008080;">do</span>
integer cb, cu
<span style="color: #004080;">integer</span> <span style="color: #000000;">cb</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
for b=3 to 6 do
<span style="color: #000000;">cu</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
cb = 0
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
cu = 0
<span style="color: #000000;">cb</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">randN</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
for i=1 to n do
<span style="color: #000000;">cu</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">unbiased</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
cb += randN(b)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
cu += unbiased(b)
<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>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1, "%d: %5.2f%% %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n})
<!--</syntaxhighlight>-->
end for</lang>
{{out}}
<small>''(Rounded to the nearest whole percent, of course)''</small>
<pre>
3: 32.83biased:33% unbiased:50.34%
4: 24.78biased:25% unbiased:50.01%
5: biased:20.21% 49.71unbiased:50%
6: 16.68biased:17% 49.67unbiased:50%
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de randN (N)
(if (= 1 (rand 1 N)) 1 0) )
 
Line 1,533 ⟶ 1,634:
(setq A (randN N))
(setq B (randN N)) ) )
A ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(for N (range 3 6)
(tab (2 1 7 2 7 2)
N ":"
Line 1,545 ⟶ 1,646:
(let S 0 (do 10000 (inc 'S (unbiased N))))
2 )
"%" ) )</langsyntaxhighlight>
Output:
<pre> 3: 33.21 % 50.48 %
Line 1,553 ⟶ 1,654:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
test: procedure options (main); /* 20 Nov. 2012 */
 
Line 1,583 ⟶ 1,684:
 
end test;
</syntaxhighlight>
</lang>
Results:
<pre>
Line 1,595 ⟶ 1,696:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function randN ( [int]$N )
{
Line 1,611 ⟶ 1,712:
return $X
}
</syntaxhighlight>
</lang>
Note: The [pscustomobject] type accelerator, used to simplify making the test output look pretty, requires version 3.0 or higher.
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Tests = 1000
ForEach ( $N in 3..6 )
Line 1,629 ⟶ 1,730:
"Unbiased Ones out of $Test" = $Unbiased }
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,641 ⟶ 1,742:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure biased(n)
If Random(n) <> 1
ProcedureReturn 0
Line 1,675 ⟶ 1,776:
output + #tab$ + " ratio=" + StrF(u_count(1) / #count * 100, 2) + "%" + #LF$
Next
MessageRequester("Biased and Unbiased random number results", output)</langsyntaxhighlight>
Sample output:
<pre>---------------------------
Line 1,694 ⟶ 1,795:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from __future__ import print_function
import random
 
Line 1,721 ⟶ 1,822:
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)), ) )</langsyntaxhighlight>
 
'''Sample output'''
Line 1,736 ⟶ 1,837:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> $ "bigrat.qky" loadfile
 
[ random 0 = ] is randN ( n --> n )
Line 1,762 ⟶ 1,863:
[ dup cr
showbias cr
showunbias cr ] </langsyntaxhighlight>
 
{{out}}
Line 1,781 ⟶ 1,882:
=={{header|R}}==
 
<langsyntaxhighlight lang="rsplus">randN = function(N) sample.int(N, 1) == 1
 
unbiased = function(f)
Line 1,791 ⟶ 1,892:
N = N,
biased = mean(replicate(samples, randN(N))),
unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))</langsyntaxhighlight>
 
Sample output:
Line 1,802 ⟶ 1,903:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
;; Using boolean #t/#f instead of 1/0
Line 1,816 ⟶ 1,917:
(printf "Count: ~a => Biased: ~a%; Unbiased: ~a%.\n"
n (try% biased) (try% (unbiased biased))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,829 ⟶ 1,930:
{{trans|Perl}}
{{works with|Rakudo|2020.08.1}}
<syntaxhighlight lang="raku" perl6line>sub randN ( $n where 3..6 ) {
return ( $n.rand / ($n - 1) ).Int;
}
Line 1,848 ⟶ 1,949:
printf "N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
$n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;
}</langsyntaxhighlight>
 
Output:<pre>N=3 randN: [676, 324], 32.4% unbiased: [517, 483], 48.3%
Line 1,856 ⟶ 1,957:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program generates unbiased random numbers and displays the results to terminal.*/
parse arg # R seed . /*obtain optional arguments from the CL*/
if #=='' | #=="," then #=1000 /*#: the number of SAMPLES to be used.*/
Line 1,874 ⟶ 1,975:
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*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,925 ⟶ 2,026:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
for n = 3 to 6
biased = 0
Line 1,945 ⟶ 2,046:
m = (random(m) = 1)
return m
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,952 ⟶ 2,053:
N = 5 : biased = 16.65%, unbiased = 48.86%
N = 6 : biased = 13.31%, unbiased = 49.96%
</pre>
 
=={{header|RPL}}==
≪ INV RAND ≥ ≫ ‘'''RandN'''’ STO
≪ 0 DUP '''WHILE''' DUP2 == '''REPEAT'''
DROP2 DUP '''RandN''' OVER '''RandN'''
'''END''' ROT DROP2
≫ ‘'''Unbiased'''’ STO
≪ 3 6 '''FOR''' n
(0,0) 1 10000 '''START'''
n '''RandN''' + n '''Unbiased''' i * →NUM +
'''NEXT''' 10000 / '''NEXT'''
≫ ‘SHOW’ STO
{{in}}
<pre>
SHOW
</pre>
{{out}}
<pre>
4: (0.3272,0.4976)
3: (0.2504,0.4961)
2: (0.201,0.5008)
1: (0.166,0.4952)
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def rand_n(bias)
rand(bias) == 0 ? 1 : 0
end
Line 1,976 ⟶ 2,102:
counter[:bias] = bias
puts counter.values_at(*keys).join("\t")
end</langsyntaxhighlight>
{{output}}
<pre>
Line 1,987 ⟶ 2,113:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">#![feature(inclusive_range_syntax)]
 
extern crate rand;
Line 2,025 ⟶ 2,151:
);
}
}</langsyntaxhighlight>
{{output}}
<pre>
Line 2,036 ⟶ 2,162:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def biased( n:Int ) = scala.util.Random.nextFloat < 1.0 / n
 
def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop }
Line 2,048 ⟶ 2,174:
"%d: %2.2f%% %2.2f%%".format(i, 100.0*c1/m, 100.0*c2/m)
}</langsyntaxhighlight>
{{output}}
<pre>3: 33.09% 49.79%
Line 2,056 ⟶ 2,182:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,089 ⟶ 2,215:
" " <& flt(100 * sumUnbiased) / flt(tests) digits 3 lpad 6);
end for;
end func;</langsyntaxhighlight>
 
Output:
Line 2,101 ⟶ 2,227:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func randN (n) {
n.rand / (n-1) -> int
}
Line 2,122 ⟶ 2,248:
printf("N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
n, [raw, fixed].map {|a| (a.dump, a[1] * 100 / iterations) }...)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,132 ⟶ 2,258:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl"># 1,0 random generator factory with 1 appearing 1/N'th of the time
proc randN n {expr {rand()*$n < 1}}
 
Line 2,154 ⟶ 2,280:
puts [format "unbiased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \
[expr {100.*$c(1)/$i}]]
}</langsyntaxhighlight>
Sample output:
<pre>
Line 2,169 ⟶ 2,295:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
Dim random As New Random()
 
Line 2,213 ⟶ 2,339:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>(N = 3): # of 0 # of 1 % of 0 % of 1
Line 2,231 ⟶ 2,357:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
 
var rand = Random.new()
Line 2,256 ⟶ 2,382:
}
Fmt.print(f, n, 100 * c1 / m, 100 * c2 / m)
}</langsyntaxhighlight>
 
{{out}}
Line 2,268 ⟶ 2,394:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn randN(N){ (not (0).random(N)).toInt() }
fcn unbiased(randN){ while((a:=randN())==randN()){} a }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">const Z=0d100_000;
foreach N in ([3..6]){
"%d: biased: %3.2f%%, unbiased: %3.2f%%".fmt(N,
Line 2,276 ⟶ 2,402:
(0).reduce(Z,'wrap(s,_){ s+unbiased(randN.fp(N)) },0.0)/Z*100)
.println();
}</langsyntaxhighlight>
{{out}}
<pre>
1,995

edits