Unbias a random generator: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: syntax coloured, rounded to nearest whole percent)
m (syntax highlighting fixup automation)
Line 16: Line 16:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F randN(n)
<syntaxhighlight lang="11l">F randN(n)
‘1,0 random generator factory with 1 appearing 1/n'th of the time’
‘1,0 random generator factory with 1 appearing 1/n'th of the time’
R () -> random:(@=n) == 0
R () -> random:(@=n) == 0
Line 35: Line 35:
v = (0.<1000000).map(x -> unbiased(@biased))
v = (0.<1000000).map(x -> unbiased(@biased))
(v1, v0) = (v.count(1), v.count(0))
(v1, v0) = (v.count(1), v.count(0))
print(‘ Unbiased: count1=#., count0=#., percent=#.2’.format(v1, v0, 100.0 * v1 / (v1 + v0)))</lang>
print(‘ Unbiased: count1=#., count0=#., percent=#.2’.format(v1, v0, 100.0 * v1 / (v1 + v0)))</syntaxhighlight>


{{out}}
{{out}}
Line 50: Line 50:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO; with Ada.Numerics.Discrete_Random;
<syntaxhighlight lang="ada">with Ada.Text_IO; with Ada.Numerics.Discrete_Random;


procedure Bias_Unbias is
procedure Bias_Unbias is
Line 100: Line 100:
Ada.Text_IO.New_Line;
Ada.Text_IO.New_Line;
end loop;
end loop;
end Bias_Unbias;</lang>
end Bias_Unbias;</syntaxhighlight>
Output:<pre> I Biased% UnBiased%
Output:<pre> I Biased% UnBiased%
3 32.87 49.80
3 32.87 49.80
Line 110: Line 110:
=={{header|Aime}}==
=={{header|Aime}}==
{{trans|C}}
{{trans|C}}
<lang aime>integer
<syntaxhighlight lang="aime">integer
biased(integer bias)
biased(integer bias)
{
{
Line 148: Line 148:


0;
0;
}</lang>
}</syntaxhighlight>
Output:<pre>bias 3: 33.51% vs 50.27%
Output:<pre>bias 3: 33.51% vs 50.27%
bias 4: 24.97% vs 49.99%
bias 4: 24.97% vs 49.99%
Line 156: Line 156:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{output?}}
{{output?}}
<lang AutoHotkey>Biased(){
<syntaxhighlight lang="autohotkey">Biased(){
Random, q, 0, 4
Random, q, 0, 4
return q=4
return q=4
Line 170: Line 170:
MsgBox % "Unbiased probability of a 1 occurring: " Errorlevel/1000
MsgBox % "Unbiased probability of a 1 occurring: " Errorlevel/1000
StringReplace, junk, t, 1, , UseErrorLevel
StringReplace, junk, t, 1, , UseErrorLevel
MsgBox % "biased probability of a 1 occurring: " Errorlevel/1000</lang>
MsgBox % "biased probability of a 1 occurring: " Errorlevel/1000</syntaxhighlight>




Line 176: Line 176:
==={{header|BASIC256}}===
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
function randN (n)
function randN (n)
if int(rand * n) + 1 <> 1 then return 0 else return 1
if int(rand * n) + 1 <> 1 then return 0 else return 1
Line 206: Line 206:
next n
next n
end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 226: Line 226:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> FOR N% = 3 TO 6
<syntaxhighlight lang="bbcbasic"> FOR N% = 3 TO 6
biased% = 0
biased% = 0
unbiased% = 0
unbiased% = 0
Line 245: Line 245:
= A%
= A%
DEF FNrandN(N%) = -(RND(N%) = 1)</lang>
DEF FNrandN(N%) = -(RND(N%) = 1)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 255: Line 255:


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 286: Line 286:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
output
output
<pre>bias 3: 33.090% vs 49.710%
<pre>bias 3: 33.090% vs 49.710%
Line 295: Line 295:
=={{header|C++}}==
=={{header|C++}}==
{{trans|C#}}
{{trans|C#}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <random>
#include <random>


Line 348: Line 348:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>(N = 3)
<pre>(N = 3)
Line 384: Line 384:
=={{header|C sharp}}==
=={{header|C sharp}}==


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace Unbias
namespace Unbias
Line 442: Line 442:
}
}
}
}
}</lang>
}</syntaxhighlight>


'''Sample Output'''
'''Sample Output'''
Line 461: Line 461:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>(defn biased [n]
<syntaxhighlight lang="clojure">(defn biased [n]
(if (< (rand 2) (/ n)) 0 1))
(if (< (rand 2) (/ n)) 0 1))


Line 477: Line 477:
[4 0.87684 0.5023]
[4 0.87684 0.5023]
[5 0.90122 0.49728]
[5 0.90122 0.49728]
[6 0.91526 0.5])</lang>
[6 0.91526 0.5])</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
biased_rand_function = (n) ->
biased_rand_function = (n) ->
# return a function that returns 0/1 with
# return a function that returns 0/1 with
Line 510: Line 510:
stats "biased", f_biased
stats "biased", f_biased
stats "unbiased", f_unbiased
stats "unbiased", f_unbiased
</syntaxhighlight>
</lang>
output
output
<pre>
<pre>
Line 533: Line 533:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun biased (n) (if (zerop (random n)) 0 1))
<syntaxhighlight lang="lisp">(defun biased (n) (if (zerop (random n)) 0 1))


(defun unbiased (n)
(defun unbiased (n)
Line 543: Line 543:
(let ((u (loop repeat 10000 collect (unbiased n)))
(let ((u (loop repeat 10000 collect (unbiased n)))
(b (loop repeat 10000 collect (biased n))))
(b (loop repeat 10000 collect (biased n))))
(format t "~a: unbiased ~d biased ~d~%" n (count 0 u) (count 0 b))))</lang>
(format t "~a: unbiased ~d biased ~d~%" n (count 0 u) (count 0 b))))</syntaxhighlight>
output
output
<pre>3: unbiased 4992 biased 3361
<pre>3: unbiased 4992 biased 3361
Line 551: Line 551:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.random, std.algorithm, std.range, std.functional;
<syntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.range, std.functional;


enum biased = (in int n) /*nothrow*/ => uniform01 < (1.0 / n);
enum biased = (in int n) /*nothrow*/ => uniform01 < (1.0 / n);
Line 567: Line 567:
M.iota.map!(_=> n.biased).sum * 100.0 / M,
M.iota.map!(_=> n.biased).sum * 100.0 / M,
M.iota.map!(_=> n.unbiased).sum * 100.0 / M);
M.iota.map!(_=> n.unbiased).sum * 100.0 / M);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3: 33.441% 49.964%
<pre>3: 33.441% 49.964%
Line 577: Line 577:
{{trans|C#}}
{{trans|C#}}
ELENA 4.x :
ELENA 4.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
extension op : IntNumber
extension op : IntNumber
Line 621: Line 621:
unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000)
unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000)
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 639: Line 639:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Random do
<syntaxhighlight lang="elixir">defmodule Random do
def randN(n) do
def randN(n) do
if :rand.uniform(n) == 1, do: 1, else: 0
if :rand.uniform(n) == 1, do: 1, else: 0
Line 655: Line 655:
ys = for _ <- 1..m, do: Random.unbiased(n)
ys = for _ <- 1..m, do: Random.unbiased(n)
IO.puts "#{n} #{Enum.sum(xs) / m} #{Enum.sum(ys) / m}"
IO.puts "#{n} #{Enum.sum(xs) / m} #{Enum.sum(ys) / m}"
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 667: Line 667:


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang ERRE>PROGRAM UNBIAS
<syntaxhighlight lang="erre">PROGRAM UNBIAS


FUNCTION RANDN(N)
FUNCTION RANDN(N)
Line 697: Line 697:
END FOR
END FOR
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>N = 3 : biased = 32.66 , unbiased = 49.14
<pre>N = 3 : biased = 32.66 , unbiased = 49.14
Line 706: Line 706:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function randN(integer N)
<syntaxhighlight lang="euphoria">function randN(integer N)
return rand(N) = 1
return rand(N) = 1
end function
end function
Line 730: Line 730:
end for
end for
printf(1, "%d: %5.2f%% %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n})
printf(1, "%d: %5.2f%% %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n})
end for</lang>
end for</syntaxhighlight>


Output:
Output:
Line 740: Line 740:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let random = Random()
let random = Random()
Line 761: Line 761:
printfn "%d: %5.2f%% %5.2f%%"
printfn "%d: %5.2f%% %5.2f%%"
b (100. * float !cb / float n) (100. * float !cu / float n)
b (100. * float !cb / float n) (100. * float !cu / float n)
0</lang>
0</syntaxhighlight>
{{out}}
{{out}}
<pre>3: 33.26% 49.97%
<pre>3: 33.26% 49.97%
Line 769: Line 769:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: formatting kernel math math.ranges random sequences ;
<syntaxhighlight lang="factor">USING: formatting kernel math math.ranges random sequences ;
IN: rosetta-code.unbias
IN: rosetta-code.unbias


Line 787: Line 787:
] each ;
] each ;


MAIN: main</lang>
MAIN: main</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 798: Line 798:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>program Bias_Unbias
<syntaxhighlight lang="fortran">program Bias_Unbias
implicit none
implicit none


Line 846: Line 846:
end function
end function


end program</lang>
end program</syntaxhighlight>
Output:
Output:
<pre>3: 33.337% 49.971%
<pre>3: 33.337% 49.971%
Line 857: Line 857:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|PureBasic}}
{{trans|PureBasic}}
<lang freebasic>
<syntaxhighlight lang="freebasic">
Function randN (n As Ubyte) As Ubyte
Function randN (n As Ubyte) As Ubyte
If Int(Rnd * n) + 1 <> 1 Then Return 0 Else Return 1
If Int(Rnd * n) + 1 <> 1 Then Return 0 Else Return 1
Line 894: Line 894:
Next n
Next n
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 922: Line 922:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>RandNGen := function(n)
<syntaxhighlight lang="gap">RandNGen := function(n)
local v, rand;
local v, rand;
v := [1 .. n - 1]*0;
v := [1 .. n - 1]*0;
Line 959: Line 959:
# [ 4, 249851, 500663 ],
# [ 4, 249851, 500663 ],
# [ 5, 200532, 500448 ],
# [ 5, 200532, 500448 ],
# [ 6, 166746, 499859 ] ]</lang>
# [ 6, 166746, 499859 ] ]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,001: Line 1,001:
u[1], u[0], float64(u[1])*100/samples)
u[1], u[0], float64(u[1])*100/samples)
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,017: Line 1,017:
=={{header|Haskell}}==
=={{header|Haskell}}==
The first task:
The first task:
<lang haskell>import Control.Monad.Random
<syntaxhighlight lang="haskell">import Control.Monad.Random
import Control.Monad
import Control.Monad
import Text.Printf
import Text.Printf


randN :: MonadRandom m => Int -> m Int
randN :: MonadRandom m => Int -> m Int
randN n = fromList [(0, fromIntegral n-1), (1, 1)]</lang>
randN n = fromList [(0, fromIntegral n-1), (1, 1)]</syntaxhighlight>


Examples of use:
Examples of use:
Line 1,031: Line 1,031:


The second task. Returns the unbiased generator for any given random generator.
The second task. Returns the unbiased generator for any given random generator.
<lang Haskell>unbiased :: (MonadRandom m, Eq x) => m x -> m x
<syntaxhighlight lang="haskell">unbiased :: (MonadRandom m, Eq x) => m x -> m x
unbiased g = do x <- g
unbiased g = do x <- g
y <- g
y <- g
if x /= y then return y else unbiased g</lang>
if x /= y then return y else unbiased g</syntaxhighlight>


Examples of use:
Examples of use:
Line 1,043: Line 1,043:


The third task:
The third task:
<lang Haskell>main = forM_ [3..6] showCounts
<syntaxhighlight lang="haskell">main = forM_ [3..6] showCounts
where
where
showCounts b = do
showCounts b = do
Line 1,050: Line 1,050:
printf "n = %d biased: %d%% unbiased: %d%%\n" b r1 r2
printf "n = %d biased: %d%% unbiased: %d%%\n" b r1 r2
counts g = (`div` 100) . length . filter (== 1) <$> replicateM 10000 g</lang>
counts g = (`div` 100) . length . filter (== 1) <$> replicateM 10000 g</syntaxhighlight>


Output:
Output:
Line 1,064: Line 1,064:
This solution works in both languages. Both <tt>randN</tt> and
This solution works in both languages. Both <tt>randN</tt> and
<tt>unbiased</tt> are generators in the Icon/Unicon sense.
<tt>unbiased</tt> are generators in the Icon/Unicon sense.
<lang unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
iters := \A[1] | 10000
iters := \A[1] | 10000
write("ratios of 0 to 1 from ",iters," trials:")
write("ratios of 0 to 1 from ",iters," trials:")
Line 1,093: Line 1,093:
procedure randN(n)
procedure randN(n)
repeat suspend if 1 = ?n then 1 else 0
repeat suspend if 1 = ?n then 1 else 0
end</lang>
end</syntaxhighlight>
and a sample run:
and a sample run:
<pre>->ubrn 100000
<pre>->ubrn 100000
Line 1,108: Line 1,108:


=={{header|J}}==
=={{header|J}}==
<lang j>randN=: 0 = ?
<syntaxhighlight lang="j">randN=: 0 = ?
unbiased=: i.@# { ::$: 2 | 0 3 -.~ _2 #.\ 4&* randN@# ]</lang>
unbiased=: i.@# { ::$: 2 | 0 3 -.~ _2 #.\ 4&* randN@# ]</syntaxhighlight>


Example use:
Example use:


<lang j> randN 10#6
<syntaxhighlight lang="j"> randN 10#6
1 0 0 0 1 0 0 0 0 0
1 0 0 0 1 0 0 0 0 0
unbiased 10#6
unbiased 10#6
1 0 0 1 0 0 1 0 1 1</lang>
1 0 0 1 0 0 1 0 1 1</syntaxhighlight>


Some example counts (these are counts of the number of 1s which appear in a test involving 100 random numbers):
Some example counts (these are counts of the number of 1s which appear in a test involving 100 random numbers):


<lang j> +/randN 100#3
<syntaxhighlight lang="j"> +/randN 100#3
30
30
+/randN 100#4
+/randN 100#4
Line 1,135: Line 1,135:
49
49
+/unbiased 100#6
+/unbiased 100#6
47</lang>
47</syntaxhighlight>


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.
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}}==
=={{header|Java}}==
<lang java>public class Bias {
<syntaxhighlight lang="java">public class Bias {
public static boolean biased(int n) {
public static boolean biased(int n) {
return Math.random() < 1.0 / n;
return Math.random() < 1.0 / n;
Line 1,166: Line 1,166:
}
}
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>3: 33,11% 50,23%
<pre>3: 33,11% 50,23%
Line 1,174: Line 1,174:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>using Printf
<syntaxhighlight lang="julia">using Printf


randN(N) = () -> rand(1:N) == 1 ? 1 : 0
randN(N) = () -> rand(1:N) == 1 ? 1 : 0
Line 1,195: Line 1,195:
v1, v0 = count(v .== 1), count(v .== 0)
v1, v0 = count(v .== 1), count(v .== 0)
@printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "unbiased", v1, v0, 100 * v1 / nrep)
@printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "unbiased", v1, v0, 100 * v1 / nrep)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,210: Line 1,210:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun biased(n: Int) = Math.random() < 1.0 / n
fun biased(n: Int) = Math.random() < 1.0 / n
Line 1,237: Line 1,237:
println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m))
println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m))
}
}
}</lang>
}</syntaxhighlight>


Sample output:
Sample output:
Line 1,248: Line 1,248:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang="lua">
local function randN(n)
local function randN(n)
return function()
return function()
Line 1,291: Line 1,291:


demonstrate(100000)
demonstrate(100000)
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,310: Line 1,310:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>rand[bias_, n_] := 1 - Unitize@RandomInteger[bias - 1, n]
<syntaxhighlight lang="mathematica">rand[bias_, n_] := 1 - Unitize@RandomInteger[bias - 1, n]
unbiased[bias_, n_] := DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]]
unbiased[bias_, n_] := DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]]
count = 1000000;
count = 1000000;
Line 1,316: Line 1,316:
Table[{n, Total[rand[n, count]]/count // N,
Table[{n, Total[rand[n, count]]/count // N,
Total[#]/Length[#] &@unbiased[n, count] // N}, {n, 3, 6}],
Total[#]/Length[#] &@unbiased[n, count] // N}, {n, 3, 6}],
TableHeadings -> {None, {n, "biased", "unbiased"}}]</lang>
TableHeadings -> {None, {n, "biased", "unbiased"}}]</syntaxhighlight>
{{out}}
{{out}}
<pre>n biased unbiased
<pre>n biased unbiased
Line 1,326: Line 1,326:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|Java}}
{{trans|Java}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
options replace format comments java crossref symbols binary


Line 1,361: Line 1,361:
end n
end n
return
return
</syntaxhighlight>
</lang>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 1,372: Line 1,372:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<lang nim>import random, sequtils, strformat
<syntaxhighlight lang="nim">import random, sequtils, strformat


type randProc = proc: range[0..1]
type randProc = proc: range[0..1]
Line 1,401: Line 1,401:
for x in v:
for x in v:
if x == 0: inc cnt0 else: inc cnt1
if x == 0: inc cnt0 else: inc cnt1
echo &"Unbiased → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"</lang>
echo &"Unbiased → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"</syntaxhighlight>


{{out}}
{{out}}
Line 1,415: Line 1,415:
=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>let randN n =
<syntaxhighlight lang="ocaml">let randN n =
if Random.int n = 0 then 1 else 0
if Random.int n = 0 then 1 else 0


Line 1,434: Line 1,434:
Printf.printf "%d: %5.2f%% %5.2f%%\n"
Printf.printf "%d: %5.2f%% %5.2f%%\n"
b (100.0 *. float !cb /. float n) (100.0 *. float !cu /. float n)
b (100.0 *. float !cb /. float n) (100.0 *. float !cu /. float n)
done</lang>
done</syntaxhighlight>


Output:
Output:
Line 1,445: Line 1,445:
=={{header|PARI/GP}}==
=={{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...
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...
<lang parigp>randN(N)=!random(N);
<syntaxhighlight lang="parigp">randN(N)=!random(N);
unbiased(N)={
unbiased(N)={
my(a,b);
my(a,b);
Line 1,454: Line 1,454:
)
)
};
};
for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n))))</lang>
for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n))))</syntaxhighlight>


Output:
Output:
Line 1,463: Line 1,463:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub randn {
<syntaxhighlight lang="perl">sub randn {
my $n = shift;
my $n = shift;
return int(rand($n) / ($n - 1));
return int(rand($n) / ($n - 1));
Line 1,483: Line 1,483:
100 * sqrt($fixed[0] * $fixed[1]) / ($fixed[0] + $fixed[1])**1.5);
100 * sqrt($fixed[0] * $fixed[1]) / ($fixed[0] + $fixed[1])**1.5);


}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>Bias 3: 6684 3316, 66.84+-0.471% fixed: 2188 2228, 49.5471+-0.752%
<pre>Bias 3: 6684 3316, 66.84+-0.471% fixed: 2188 2228, 49.5471+-0.752%
Line 1,491: Line 1,491:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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: 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: #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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<small>''(Rounded to the nearest whole percent, of course)''</small>
<small>''(Rounded to the nearest whole percent, of course)''</small>
Line 1,527: Line 1,527:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de randN (N)
<syntaxhighlight lang="picolisp">(de randN (N)
(if (= 1 (rand 1 N)) 1 0) )
(if (= 1 (rand 1 N)) 1 0) )


Line 1,536: Line 1,536:
(setq A (randN N))
(setq A (randN N))
(setq B (randN N)) ) )
(setq B (randN N)) ) )
A ) )</lang>
A ) )</syntaxhighlight>
Test:
Test:
<lang PicoLisp>(for N (range 3 6)
<syntaxhighlight lang="picolisp">(for N (range 3 6)
(tab (2 1 7 2 7 2)
(tab (2 1 7 2 7 2)
N ":"
N ":"
Line 1,548: Line 1,548:
(let S 0 (do 10000 (inc 'S (unbiased N))))
(let S 0 (do 10000 (inc 'S (unbiased N))))
2 )
2 )
"%" ) )</lang>
"%" ) )</syntaxhighlight>
Output:
Output:
<pre> 3: 33.21 % 50.48 %
<pre> 3: 33.21 % 50.48 %
Line 1,556: Line 1,556:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
test: procedure options (main); /* 20 Nov. 2012 */
test: procedure options (main); /* 20 Nov. 2012 */


Line 1,586: Line 1,586:


end test;
end test;
</syntaxhighlight>
</lang>
Results:
Results:
<pre>
<pre>
Line 1,598: Line 1,598:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function randN ( [int]$N )
function randN ( [int]$N )
{
{
Line 1,614: Line 1,614:
return $X
return $X
}
}
</syntaxhighlight>
</lang>
Note: The [pscustomobject] type accelerator, used to simplify making the test output look pretty, requires version 3.0 or higher.
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
$Tests = 1000
ForEach ( $N in 3..6 )
ForEach ( $N in 3..6 )
Line 1,632: Line 1,632:
"Unbiased Ones out of $Test" = $Unbiased }
"Unbiased Ones out of $Test" = $Unbiased }
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,644: Line 1,644:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure biased(n)
<syntaxhighlight lang="purebasic">Procedure biased(n)
If Random(n) <> 1
If Random(n) <> 1
ProcedureReturn 0
ProcedureReturn 0
Line 1,678: Line 1,678:
output + #tab$ + " ratio=" + StrF(u_count(1) / #count * 100, 2) + "%" + #LF$
output + #tab$ + " ratio=" + StrF(u_count(1) / #count * 100, 2) + "%" + #LF$
Next
Next
MessageRequester("Biased and Unbiased random number results", output)</lang>
MessageRequester("Biased and Unbiased random number results", output)</syntaxhighlight>
Sample output:
Sample output:
<pre>---------------------------
<pre>---------------------------
Line 1,697: Line 1,697:


=={{header|Python}}==
=={{header|Python}}==
<lang python>from __future__ import print_function
<syntaxhighlight lang="python">from __future__ import print_function
import random
import random


Line 1,724: Line 1,724:
v = [unbiased(biased) for x in range(1000000)]
v = [unbiased(biased) for x in range(1000000)]
v1, v0 = v.count(1), v.count(0)
v1, v0 = v.count(1), v.count(0)
print ( " Unbiased = %r" % (Stats(v1, v0, 100. * v1/(v1 + v0)), ) )</lang>
print ( " Unbiased = %r" % (Stats(v1, v0, 100. * v1/(v1 + v0)), ) )</syntaxhighlight>


'''Sample output'''
'''Sample output'''
Line 1,739: Line 1,739:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> $ "bigrat.qky" loadfile
<syntaxhighlight lang="quackery"> $ "bigrat.qky" loadfile


[ random 0 = ] is randN ( n --> n )
[ random 0 = ] is randN ( n --> n )
Line 1,765: Line 1,765:
[ dup cr
[ dup cr
showbias cr
showbias cr
showunbias cr ] </lang>
showunbias cr ] </syntaxhighlight>


{{out}}
{{out}}
Line 1,784: Line 1,784:
=={{header|R}}==
=={{header|R}}==


<lang rsplus>randN = function(N) sample.int(N, 1) == 1
<syntaxhighlight lang="rsplus">randN = function(N) sample.int(N, 1) == 1


unbiased = function(f)
unbiased = function(f)
Line 1,794: Line 1,794:
N = N,
N = N,
biased = mean(replicate(samples, randN(N))),
biased = mean(replicate(samples, randN(N))),
unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))</lang>
unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))</syntaxhighlight>


Sample output:
Sample output:
Line 1,805: Line 1,805:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
;; Using boolean #t/#f instead of 1/0
;; Using boolean #t/#f instead of 1/0
Line 1,819: Line 1,819:
(printf "Count: ~a => Biased: ~a%; Unbiased: ~a%.\n"
(printf "Count: ~a => Biased: ~a%; Unbiased: ~a%.\n"
n (try% biased) (try% (unbiased biased))))
n (try% biased) (try% (unbiased biased))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,832: Line 1,832:
{{trans|Perl}}
{{trans|Perl}}
{{works with|Rakudo|2020.08.1}}
{{works with|Rakudo|2020.08.1}}
<lang perl6>sub randN ( $n where 3..6 ) {
<syntaxhighlight lang="raku" line>sub randN ( $n where 3..6 ) {
return ( $n.rand / ($n - 1) ).Int;
return ( $n.rand / ($n - 1) ).Int;
}
}
Line 1,851: Line 1,851:
printf "N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
printf "N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
$n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;
$n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;
}</lang>
}</syntaxhighlight>


Output:<pre>N=3 randN: [676, 324], 32.4% unbiased: [517, 483], 48.3%
Output:<pre>N=3 randN: [676, 324], 32.4% unbiased: [517, 483], 48.3%
Line 1,859: Line 1,859:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program generates unbiased random numbers and displays the results to terminal.*/
<syntaxhighlight lang="rexx">/*REXX program generates unbiased random numbers and displays the results to terminal.*/
parse arg # R seed . /*obtain optional arguments from the CL*/
parse arg # R seed . /*obtain optional arguments from the CL*/
if #=='' | #=="," then #=1000 /*#: the number of SAMPLES to be used.*/
if #=='' | #=="," then #=1000 /*#: the number of SAMPLES to be used.*/
Line 1,877: Line 1,877:
pct: return ctr( format(arg(1) / # * 100, , 2)'%' ) /*2 decimal digits.*/
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.*/
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*/</lang>
unbiased: do until x\==randN(N); x=randN(N); end; return x /* " unbiased RAND*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 1,928: Line 1,928:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
for n = 3 to 6
for n = 3 to 6
biased = 0
biased = 0
Line 1,948: Line 1,948:
m = (random(m) = 1)
m = (random(m) = 1)
return m
return m
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,958: Line 1,958:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def rand_n(bias)
<syntaxhighlight lang="ruby">def rand_n(bias)
rand(bias) == 0 ? 1 : 0
rand(bias) == 0 ? 1 : 0
end
end
Line 1,979: Line 1,979:
counter[:bias] = bias
counter[:bias] = bias
puts counter.values_at(*keys).join("\t")
puts counter.values_at(*keys).join("\t")
end</lang>
end</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 1,990: Line 1,990:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>#![feature(inclusive_range_syntax)]
<syntaxhighlight lang="rust">#![feature(inclusive_range_syntax)]


extern crate rand;
extern crate rand;
Line 2,028: Line 2,028:
);
);
}
}
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 2,039: Line 2,039:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def biased( n:Int ) = scala.util.Random.nextFloat < 1.0 / n
<syntaxhighlight 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 }
def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop }
Line 2,051: Line 2,051:
"%d: %2.2f%% %2.2f%%".format(i, 100.0*c1/m, 100.0*c2/m)
"%d: %2.2f%% %2.2f%%".format(i, 100.0*c1/m, 100.0*c2/m)
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>3: 33.09% 49.79%
<pre>3: 33.09% 49.79%
Line 2,059: Line 2,059:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";


Line 2,092: Line 2,092:
" " <& flt(100 * sumUnbiased) / flt(tests) digits 3 lpad 6);
" " <& flt(100 * sumUnbiased) / flt(tests) digits 3 lpad 6);
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


Output:
Output:
Line 2,104: Line 2,104:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Raku}}
{{trans|Raku}}
<lang ruby>func randN (n) {
<syntaxhighlight lang="ruby">func randN (n) {
n.rand / (n-1) -> int
n.rand / (n-1) -> int
}
}
Line 2,125: Line 2,125:
printf("N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
printf("N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
n, [raw, fixed].map {|a| (a.dump, a[1] * 100 / iterations) }...)
n, [raw, fixed].map {|a| (a.dump, a[1] * 100 / iterations) }...)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,135: Line 2,135:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl># 1,0 random generator factory with 1 appearing 1/N'th of the time
<syntaxhighlight lang="tcl"># 1,0 random generator factory with 1 appearing 1/N'th of the time
proc randN n {expr {rand()*$n < 1}}
proc randN n {expr {rand()*$n < 1}}


Line 2,157: Line 2,157:
puts [format "unbiased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \
puts [format "unbiased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \
[expr {100.*$c(1)/$i}]]
[expr {100.*$c(1)/$i}]]
}</lang>
}</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 2,172: Line 2,172:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1
Dim random As New Random()
Dim random As New Random()


Line 2,216: Line 2,216:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>(N = 3): # of 0 # of 1 % of 0 % of 1
<pre>(N = 3): # of 0 # of 1 % of 0 % of 1
Line 2,234: Line 2,234:
{{trans|Kotlin}}
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "random" for Random
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 2,259: Line 2,259:
}
}
Fmt.print(f, n, 100 * c1 / m, 100 * c2 / m)
Fmt.print(f, n, 100 * c1 / m, 100 * c2 / m)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,271: Line 2,271:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn randN(N){ (not (0).random(N)).toInt() }
<syntaxhighlight lang="zkl">fcn randN(N){ (not (0).random(N)).toInt() }
fcn unbiased(randN){ while((a:=randN())==randN()){} a }</lang>
fcn unbiased(randN){ while((a:=randN())==randN()){} a }</syntaxhighlight>
<lang zkl>const Z=0d100_000;
<syntaxhighlight lang="zkl">const Z=0d100_000;
foreach N in ([3..6]){
foreach N in ([3..6]){
"%d: biased: %3.2f%%, unbiased: %3.2f%%".fmt(N,
"%d: biased: %3.2f%%, unbiased: %3.2f%%".fmt(N,
Line 2,279: Line 2,279:
(0).reduce(Z,'wrap(s,_){ s+unbiased(randN.fp(N)) },0.0)/Z*100)
(0).reduce(Z,'wrap(s,_){ s+unbiased(randN.fp(N)) },0.0)/Z*100)
.println();
.println();
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>