Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
2
Task/Unbias-a-random-generator/00-META.yaml
Normal file
2
Task/Unbias-a-random-generator/00-META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Unbias_a_random_generator
|
||||
14
Task/Unbias-a-random-generator/00-TASK.txt
Normal file
14
Task/Unbias-a-random-generator/00-TASK.txt
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
Given a weighted one-bit generator of random numbers where the probability of a one occurring, <math>P_1</math>, is not the same as <math>P_0</math>, the probability of a zero occurring, 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>.
|
||||
|
||||
|
||||
;Task details:
|
||||
* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
|
||||
* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
|
||||
* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
|
||||
|
||||
<br>
|
||||
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
|
||||
|
||||
This task is an implementation of [http://en.wikipedia.org/wiki/Randomness_extractor#Von_Neumann_extractor Von Neumann debiasing], first described in a 1951 paper.
|
||||
<br><br>
|
||||
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
F randN(n)
|
||||
‘1,0 random generator factory with 1 appearing 1/n'th of the time’
|
||||
R () -> random:(@=n) == 0
|
||||
|
||||
F unbiased(biased)
|
||||
‘uses a biased() generator of 1 or 0, to create an unbiased one’
|
||||
V (this, that) = (biased(), biased())
|
||||
L this == that
|
||||
(this, that) = (biased(), biased())
|
||||
R this
|
||||
|
||||
L(n) 3..6
|
||||
V biased = randN(n)
|
||||
V v = (0.<1000000).map(x -> @biased())
|
||||
V (v1, v0) = (v.count(1), v.count(0))
|
||||
print(‘Biased(#.): count1=#., count0=#., percent=#.2’.format(n, v1, v0, 100.0 * v1 / (v1 + v0)))
|
||||
|
||||
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)))
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
with Ada.Text_IO; with Ada.Numerics.Discrete_Random;
|
||||
|
||||
procedure Bias_Unbias is
|
||||
|
||||
Modulus: constant Integer := 60; -- lcm of {3,4,5,6}
|
||||
type M is mod Modulus;
|
||||
package Rand is new Ada.Numerics.Discrete_Random(M);
|
||||
Gen: Rand.Generator;
|
||||
|
||||
subtype Bit is Integer range 0 .. 1;
|
||||
|
||||
function Biased_Bit(Bias_Base: Integer) return Bit is
|
||||
begin
|
||||
if (Integer(Rand.Random(Gen))* Bias_Base) / Modulus > 0 then
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
end if;
|
||||
end Biased_Bit;
|
||||
|
||||
function Unbiased_Bit(Bias_Base: Integer) return Bit is
|
||||
A, B: Bit := 0;
|
||||
begin
|
||||
while A = B loop
|
||||
A := Biased_Bit(Bias_Base);
|
||||
B := Biased_Bit(Bias_Base);
|
||||
end loop;
|
||||
return A;
|
||||
end Unbiased_Bit;
|
||||
|
||||
package FIO is new Ada.Text_IO.Float_IO(Float);
|
||||
|
||||
Counter_B, Counter_U: Natural;
|
||||
Number_Of_Samples: constant Natural := 10_000;
|
||||
|
||||
begin
|
||||
Rand.Reset(Gen);
|
||||
Ada.Text_IO.Put_Line(" I Biased% UnBiased%");
|
||||
for I in 3 .. 6 loop
|
||||
Counter_B := 0;
|
||||
Counter_U := 0;
|
||||
for J in 1 .. Number_Of_Samples loop
|
||||
Counter_B := Counter_B + Biased_Bit(I);
|
||||
Counter_U := Counter_U + Unbiased_Bit(I);
|
||||
end loop;
|
||||
Ada.Text_IO.Put(Integer'Image(I));
|
||||
FIO.Put(100.0 * Float(Counter_B) / Float(Number_Of_Samples), 5, 2, 0);
|
||||
FIO.Put(100.0 * Float(Counter_U) / Float(Number_Of_Samples), 5, 2, 0);
|
||||
Ada.Text_IO.New_Line;
|
||||
end loop;
|
||||
end Bias_Unbias;
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
integer
|
||||
biased(integer bias)
|
||||
{
|
||||
1 ^ min(drand(bias - 1), 1);
|
||||
}
|
||||
|
||||
integer
|
||||
unbiased(integer bias)
|
||||
{
|
||||
integer a;
|
||||
|
||||
while ((a = biased(bias)) == biased(bias)) {
|
||||
}
|
||||
|
||||
a;
|
||||
}
|
||||
|
||||
integer
|
||||
main(void)
|
||||
{
|
||||
integer b, n, cb, cu, i;
|
||||
|
||||
n = 10000;
|
||||
b = 3;
|
||||
while (b <= 6) {
|
||||
i = cb = cu = 0;
|
||||
while ((i += 1) <= n) {
|
||||
cb += biased(b);
|
||||
cu += unbiased(b);
|
||||
}
|
||||
|
||||
o_form("bias ~: /d2p2/%% vs /d2p2/%%\n", b, 100r * cb / n,
|
||||
100r * cu / n);
|
||||
|
||||
b += 1;
|
||||
}
|
||||
|
||||
0;
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
Biased(){
|
||||
Random, q, 0, 4
|
||||
return q=4
|
||||
}
|
||||
Unbiased(){
|
||||
Loop
|
||||
If ((a := Biased()) != biased())
|
||||
return a
|
||||
}
|
||||
Loop 1000
|
||||
t .= biased(), t2 .= unbiased()
|
||||
StringReplace, junk, t2, 1, , UseErrorLevel
|
||||
MsgBox % "Unbiased probability of a 1 occurring: " Errorlevel/1000
|
||||
StringReplace, junk, t, 1, , UseErrorLevel
|
||||
MsgBox % "biased probability of a 1 occurring: " Errorlevel/1000
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
function randN (n)
|
||||
if int(rand * n) + 1 <> 1 then return 0 else return 1
|
||||
end function
|
||||
|
||||
function unbiased (n)
|
||||
do
|
||||
a = randN (n)
|
||||
b = randN (n)
|
||||
until a <> b
|
||||
return a
|
||||
end function
|
||||
|
||||
numveces = 100000
|
||||
|
||||
print "Resultados de números aleatorios sesgados e imparciales" + chr(10)
|
||||
for n = 3 to 6
|
||||
dim b_numveces(n) fill 0
|
||||
dim u_numveces(n) fill 0
|
||||
for m = 1 to numveces
|
||||
x = randN (n)
|
||||
b_numveces[x] += 1
|
||||
x = unbiased (n)
|
||||
u_numveces[x] += 1
|
||||
next m
|
||||
print "N = "; n
|
||||
print " Biased =>", "#0="; (b_numveces[0]); " #1="; (b_numveces[1]); " ratio = "; (b_numveces[1]/numveces*100); "%"
|
||||
print "Unbiased =>", "#0="; (u_numveces[0]); " #1="; (u_numveces[1]); " ratio = "; (u_numveces[1]/numveces*100); "%"
|
||||
next n
|
||||
end
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
FOR N% = 3 TO 6
|
||||
biased% = 0
|
||||
unbiased% = 0
|
||||
FOR I% = 1 TO 10000
|
||||
IF FNrandN(N%) biased% += 1
|
||||
IF FNunbiased(N%) unbiased% += 1
|
||||
NEXT
|
||||
PRINT "N = ";N% " : biased = "; biased%/100 "%, unbiased = "; unbiased%/100 "%"
|
||||
NEXT
|
||||
END
|
||||
|
||||
DEF FNunbiased(N%)
|
||||
LOCAL A%,B%
|
||||
REPEAT
|
||||
A% = FNrandN(N%)
|
||||
B% = FNrandN(N%)
|
||||
UNTIL A%<>B%
|
||||
= A%
|
||||
|
||||
DEF FNrandN(N%) = -(RND(N%) = 1)
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
#include <iostream>
|
||||
#include <random>
|
||||
|
||||
std::default_random_engine generator;
|
||||
bool biased(int n) {
|
||||
std::uniform_int_distribution<int> distribution(1, n);
|
||||
return distribution(generator) == 1;
|
||||
}
|
||||
|
||||
bool unbiased(int n) {
|
||||
bool flip1, flip2;
|
||||
|
||||
/* Flip twice, and check if the values are the same.
|
||||
* If so, flip again. Otherwise, return the value of the first flip. */
|
||||
|
||||
do {
|
||||
flip1 = biased(n);
|
||||
flip2 = biased(n);
|
||||
} while (flip1 == flip2);
|
||||
|
||||
return flip1;
|
||||
}
|
||||
|
||||
int main() {
|
||||
for (size_t n = 3; n <= 6; n++) {
|
||||
int biasedZero = 0;
|
||||
int biasedOne = 0;
|
||||
int unbiasedZero = 0;
|
||||
int unbiasedOne = 0;
|
||||
|
||||
for (size_t i = 0; i < 100000; i++) {
|
||||
if (biased(n)) {
|
||||
biasedOne++;
|
||||
} else {
|
||||
biasedZero++;
|
||||
}
|
||||
if (unbiased(n)) {
|
||||
unbiasedOne++;
|
||||
} else {
|
||||
unbiasedZero++;
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << "(N = " << n << ")\n";
|
||||
std::cout << "Biased:\n";
|
||||
std::cout << " 0 = " << biasedZero << "; " << biasedZero / 1000.0 << "%\n";
|
||||
std::cout << " 1 = " << biasedOne << "; " << biasedOne / 1000.0 << "%\n";
|
||||
std::cout << "Unbiased:\n";
|
||||
std::cout << " 0 = " << unbiasedZero << "; " << unbiasedZero / 1000.0 << "%\n";
|
||||
std::cout << " 1 = " << unbiasedOne << "; " << unbiasedOne / 1000.0 << "%\n";
|
||||
std::cout << '\n';
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
using System;
|
||||
|
||||
namespace Unbias
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
// Demonstrate.
|
||||
for (int n = 3; n <= 6; n++)
|
||||
{
|
||||
int biasedZero = 0, biasedOne = 0, unbiasedZero = 0, unbiasedOne = 0;
|
||||
for (int i = 0; i < 100000; i++)
|
||||
{
|
||||
if (randN(n))
|
||||
biasedOne++;
|
||||
else
|
||||
biasedZero++;
|
||||
if (Unbiased(n))
|
||||
unbiasedOne++;
|
||||
else
|
||||
unbiasedZero++;
|
||||
}
|
||||
|
||||
Console.WriteLine("(N = {0}):".PadRight(17) + "# of 0\t# of 1\t% of 0\t% of 1", n);
|
||||
Console.WriteLine("Biased:".PadRight(15) + "{0}\t{1}\t{2}\t{3}",
|
||||
biasedZero, biasedOne,
|
||||
biasedZero/1000, biasedOne/1000);
|
||||
Console.WriteLine("Unbiased:".PadRight(15) + "{0}\t{1}\t{2}\t{3}",
|
||||
unbiasedZero, unbiasedOne,
|
||||
unbiasedZero/1000, unbiasedOne/1000);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Unbiased(int n)
|
||||
{
|
||||
bool flip1, flip2;
|
||||
|
||||
/* Flip twice, and check if the values are the same.
|
||||
* If so, flip again. Otherwise, return the value of the first flip. */
|
||||
|
||||
do
|
||||
{
|
||||
flip1 = randN(n);
|
||||
flip2 = randN(n);
|
||||
} while (flip1 == flip2);
|
||||
|
||||
return flip1;
|
||||
}
|
||||
|
||||
private static readonly Random random = new Random();
|
||||
|
||||
private static bool randN(int n)
|
||||
{
|
||||
// Has an 1/n chance of returning 1. Otherwise it returns 0.
|
||||
return random.Next(0, n) == 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
32
Task/Unbias-a-random-generator/C/unbias-a-random-generator.c
Normal file
32
Task/Unbias-a-random-generator/C/unbias-a-random-generator.c
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int biased(int bias)
|
||||
{
|
||||
/* balance out the bins, being pedantic */
|
||||
int r, rand_max = RAND_MAX - (RAND_MAX % bias);
|
||||
while ((r = rand()) > rand_max);
|
||||
return r < rand_max / bias;
|
||||
}
|
||||
|
||||
int unbiased(int bias)
|
||||
{
|
||||
int a;
|
||||
while ((a = biased(bias)) == biased(bias));
|
||||
return a;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int b, n = 10000, cb, cu, i;
|
||||
for (b = 3; b <= 6; b++) {
|
||||
for (i = cb = cu = 0; i < n; i++) {
|
||||
cb += biased(b);
|
||||
cu += unbiased(b);
|
||||
}
|
||||
printf("bias %d: %5.3f%% vs %5.3f%%\n", b,
|
||||
100. * cb / n, 100. * cu / n);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
(defn biased [n]
|
||||
(if (< (rand 2) (/ n)) 0 1))
|
||||
|
||||
(defn unbiased [n]
|
||||
(loop [a 0 b 0]
|
||||
(if (= a b)
|
||||
(recur (biased n) (biased n))
|
||||
a)))
|
||||
|
||||
(for [n (range 3 7)]
|
||||
[n
|
||||
(double (/ (apply + (take 50000 (repeatedly #(biased n)))) 50000))
|
||||
(double (/ (apply + (take 50000 (repeatedly #(unbiased n)))) 50000))])
|
||||
([3 0.83292 0.50422]
|
||||
[4 0.87684 0.5023]
|
||||
[5 0.90122 0.49728]
|
||||
[6 0.91526 0.5])
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
biased_rand_function = (n) ->
|
||||
# return a function that returns 0/1 with
|
||||
# 1 appearing only 1/Nth of the time
|
||||
cap = 1/n
|
||||
->
|
||||
if Math.random() < cap
|
||||
1
|
||||
else
|
||||
0
|
||||
|
||||
unbiased_function = (f) ->
|
||||
->
|
||||
while true
|
||||
[n1, n2] = [f(), f()]
|
||||
return n1 if n1 + n2 == 1
|
||||
|
||||
stats = (label, f) ->
|
||||
cnt = 0
|
||||
sample_size = 10000000
|
||||
for i in [1...sample_size]
|
||||
cnt += 1 if f() == 1
|
||||
console.log "ratio of 1s: #{cnt / sample_size} [#{label}]"
|
||||
|
||||
for n in [3..6]
|
||||
console.log "\n---------- n = #{n}"
|
||||
f_biased = biased_rand_function(n)
|
||||
f_unbiased = unbiased_function f_biased
|
||||
stats "biased", f_biased
|
||||
stats "unbiased", f_unbiased
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
(defun biased (n) (if (zerop (random n)) 0 1))
|
||||
|
||||
(defun unbiased (n)
|
||||
(loop with x do
|
||||
(if (/= (setf x (biased n)) (biased n))
|
||||
(return x))))
|
||||
|
||||
(loop for n from 3 to 6 do
|
||||
(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))))
|
||||
17
Task/Unbias-a-random-generator/D/unbias-a-random-generator.d
Normal file
17
Task/Unbias-a-random-generator/D/unbias-a-random-generator.d
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import std.stdio, std.random, std.algorithm, std.range, std.functional;
|
||||
|
||||
enum biased = (in int n) /*nothrow*/ => uniform01 < (1.0 / n);
|
||||
|
||||
int unbiased(in int bias) /*nothrow*/ {
|
||||
int a;
|
||||
while ((a = bias.biased) == bias.biased) {}
|
||||
return a;
|
||||
}
|
||||
|
||||
void main() {
|
||||
enum M = 500_000;
|
||||
foreach (immutable n; 3 .. 7)
|
||||
writefln("%d: %2.3f%% %2.3f%%", n,
|
||||
M.iota.map!(_=> n.biased).sum * 100.0 / M,
|
||||
M.iota.map!(_=> n.unbiased).sum * 100.0 / M);
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
PROGRAM UNBIAS
|
||||
|
||||
FUNCTION RANDN(N)
|
||||
RANDN=INT(1+N*RND(1))=1
|
||||
END FUNCTION
|
||||
|
||||
PROCEDURE UNBIASED(N->RIS)
|
||||
LOCAL A,B
|
||||
REPEAT
|
||||
A=RANDN(N)
|
||||
B=RANDN(N)
|
||||
UNTIL A<>B
|
||||
RIS=A
|
||||
END PROCEDURE
|
||||
|
||||
BEGIN
|
||||
PRINT(CHR$(12);) ! CLS
|
||||
RANDOMIZE(TIMER)
|
||||
|
||||
FOR N=3 TO 6 DO
|
||||
BIASED=0
|
||||
UNBIASED=0
|
||||
FOR I=1 TO 10000 DO
|
||||
IF RANDN(N) THEN biased+=1
|
||||
UNBIASED(N->RIS)
|
||||
IF RIS THEN unbiased+=+1
|
||||
END FOR
|
||||
PRINT("N =";N;" : biased =";biased/100;", unbiased =";unbiased/100)
|
||||
END FOR
|
||||
END PROGRAM
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
import extensions;
|
||||
|
||||
extension op : IntNumber
|
||||
{
|
||||
bool randN()
|
||||
= randomGenerator.nextInt(self) == 0;
|
||||
|
||||
get bool Unbiased()
|
||||
{
|
||||
bool flip1 := self.randN();
|
||||
bool flip2 := self.randN();
|
||||
|
||||
while (flip1 == flip2)
|
||||
{
|
||||
flip1 := self.randN();
|
||||
flip2 := self.randN()
|
||||
};
|
||||
|
||||
^ flip1
|
||||
}
|
||||
}
|
||||
|
||||
public program()
|
||||
{
|
||||
for(int n := 3, n <= 6, n += 1)
|
||||
{
|
||||
int biasedZero := 0;
|
||||
int biasedOne := 0;
|
||||
int unbiasedZero := 0;
|
||||
int unbiasedOne := 0;
|
||||
|
||||
for(int i := 0, i < 100000, i += 1)
|
||||
{
|
||||
if(n.randN()) { biasedOne += 1 } else { biasedZero += 1 };
|
||||
if(n.Unbiased) { unbiasedOne += 1 } else { unbiasedZero += 1 }
|
||||
};
|
||||
|
||||
console
|
||||
.printLineFormatted("(N = {0}):".padRight(17) + "# of 0"$9"# of 1"$9"% of 0"$9"% of 1", n)
|
||||
.printLineFormatted("Biased:".padRight(15) + "{0}"$9"{1}"$9"{2}"$9"{3}",
|
||||
biasedZero, biasedOne, biasedZero / 1000, biasedOne / 1000)
|
||||
.printLineFormatted("Unbiased:".padRight(15) + "{0}"$9"{1}"$9"{2}"$9"{3}",
|
||||
unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
defmodule Random do
|
||||
def randN(n) do
|
||||
if :rand.uniform(n) == 1, do: 1, else: 0
|
||||
end
|
||||
def unbiased(n) do
|
||||
{x, y} = {randN(n), randN(n)}
|
||||
if x != y, do: x, else: unbiased(n)
|
||||
end
|
||||
end
|
||||
|
||||
IO.puts "N biased unbiased"
|
||||
m = 10000
|
||||
for n <- 3..6 do
|
||||
xs = for _ <- 1..m, do: Random.randN(n)
|
||||
ys = for _ <- 1..m, do: Random.unbiased(n)
|
||||
IO.puts "#{n} #{Enum.sum(xs) / m} #{Enum.sum(ys) / m}"
|
||||
end
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
function randN(integer N)
|
||||
return rand(N) = 1
|
||||
end function
|
||||
|
||||
function unbiased(integer N)
|
||||
integer a
|
||||
while 1 do
|
||||
a = randN(N)
|
||||
if a != randN(N) then
|
||||
return a
|
||||
end if
|
||||
end while
|
||||
end function
|
||||
|
||||
constant n = 10000
|
||||
integer cb, cu
|
||||
for b = 3 to 6 do
|
||||
cb = 0
|
||||
cu = 0
|
||||
for i = 1 to n do
|
||||
cb += randN(b)
|
||||
cu += unbiased(b)
|
||||
end for
|
||||
printf(1, "%d: %5.2f%% %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n})
|
||||
end for
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
open System
|
||||
|
||||
let random = Random()
|
||||
|
||||
let randN = random.Next >> (=)0 >> Convert.ToInt32
|
||||
|
||||
let rec unbiased n =
|
||||
let a = randN n
|
||||
if a <> randN n then a else unbiased n
|
||||
|
||||
[<EntryPoint>]
|
||||
let main argv =
|
||||
let n = if argv.Length > 0 then UInt32.Parse(argv.[0]) |> int else 100000
|
||||
for b = 3 to 6 do
|
||||
let cb = ref 0
|
||||
let cu = ref 0
|
||||
for i = 1 to n do
|
||||
cb := !cb + randN b
|
||||
cu := !cu + unbiased b
|
||||
printfn "%d: %5.2f%% %5.2f%%"
|
||||
b (100. * float !cb / float n) (100. * float !cu / float n)
|
||||
0
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
USING: formatting kernel math math.ranges random sequences ;
|
||||
IN: rosetta-code.unbias
|
||||
|
||||
: randN ( n -- m ) random zero? 1 0 ? ;
|
||||
|
||||
: unbiased ( n -- m )
|
||||
dup [ randN ] dup bi 2dup = not
|
||||
[ drop nip ] [ 2drop unbiased ] if ;
|
||||
|
||||
: test-generator ( quot -- x )
|
||||
[ 1,000,000 dup ] dip replicate sum 100 * swap / ; inline
|
||||
|
||||
: main ( -- )
|
||||
3 6 [a,b] [
|
||||
dup [ randN ] [ unbiased ] bi-curry
|
||||
[ test-generator ] bi@ "%d: %.2f%% %.2f%%\n" printf
|
||||
] each ;
|
||||
|
||||
MAIN: main
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
program Bias_Unbias
|
||||
implicit none
|
||||
|
||||
integer, parameter :: samples = 1000000
|
||||
integer :: i, j
|
||||
integer :: c1, c2, rand
|
||||
|
||||
do i = 3, 6
|
||||
c1 = 0
|
||||
c2 = 0
|
||||
do j = 1, samples
|
||||
rand = bias(i)
|
||||
if (rand == 1) c1 = c1 + 1
|
||||
rand = unbias(i)
|
||||
if (rand == 1) c2 = c2 + 1
|
||||
end do
|
||||
write(*, "(i2,a,f8.3,a,f8.3,a)") i, ":", real(c1) * 100.0 / real(samples), &
|
||||
"%", real(c2) * 100.0 / real(samples), "%"
|
||||
end do
|
||||
|
||||
contains
|
||||
|
||||
function bias(n)
|
||||
integer :: bias
|
||||
integer, intent(in) :: n
|
||||
real :: r
|
||||
|
||||
call random_number(r)
|
||||
if (r > 1 / real(n)) then
|
||||
bias = 0
|
||||
else
|
||||
bias = 1
|
||||
end if
|
||||
end function
|
||||
|
||||
function unbias(n)
|
||||
integer :: unbias
|
||||
integer, intent(in) :: n
|
||||
integer :: a, b
|
||||
|
||||
do
|
||||
a = bias(n)
|
||||
b = bias(n)
|
||||
if (a /= b) exit
|
||||
end do
|
||||
unbias = a
|
||||
end function
|
||||
|
||||
end program
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
Function randN (n As Ubyte) As Ubyte
|
||||
If Int(Rnd * n) + 1 <> 1 Then Return 0 Else Return 1
|
||||
End Function
|
||||
|
||||
Function unbiased (n As Ubyte) As Ubyte
|
||||
Dim As Ubyte a, b
|
||||
Do
|
||||
a = randN (n)
|
||||
b = randN (n)
|
||||
Loop Until a <> b
|
||||
Return a
|
||||
End Function
|
||||
|
||||
Const count = 100000
|
||||
|
||||
Dim x As Ubyte
|
||||
|
||||
Randomize Timer
|
||||
|
||||
Print "Resultados de n";Chr(163);!"meros aleatorios sesgados e imparciales\n"
|
||||
For n As Ubyte = 3 To 6
|
||||
Dim As Integer b_count(1)
|
||||
Dim As Integer u_count(1)
|
||||
For m As Integer = 1 To count
|
||||
x = randN (n)
|
||||
b_count(x) += 1
|
||||
x = unbiased (n)
|
||||
u_count(x) += 1
|
||||
Next m
|
||||
Print "N ="; n
|
||||
Print " Biased =>", "#0="; Str(b_count(0)), "#1="; Str(b_count(1)),
|
||||
Print Using "ratio = ##.##%"; (b_count(1) / count * 100)
|
||||
Print "Unbiased =>", "#0="; Str(u_count(0)), "#1="; Str(u_count(1)),
|
||||
Print Using "ratio = ##.##%"; (u_count(1) / count * 100)
|
||||
Next n
|
||||
Sleep
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
RandNGen := function(n)
|
||||
local v, rand;
|
||||
v := [1 .. n - 1]*0;
|
||||
Add(v, 1);
|
||||
rand := function()
|
||||
return Random(v);
|
||||
end;
|
||||
return rand;
|
||||
end;
|
||||
|
||||
UnbiasedGen := function(rand)
|
||||
local unbiased;
|
||||
unbiased := function()
|
||||
local a, b;
|
||||
while true do
|
||||
a := rand();
|
||||
b := rand();
|
||||
if a <> b then
|
||||
break;
|
||||
fi;
|
||||
od;
|
||||
return a;
|
||||
end;
|
||||
return unbiased;
|
||||
end;
|
||||
|
||||
range := [2 .. 6];
|
||||
v := List(range, RandNGen);
|
||||
w := List(v, UnbiasedGen);
|
||||
apply := gen -> Sum([1 .. 1000000], n -> gen());
|
||||
|
||||
# Some tests (2 is added as a witness, since in this case RandN is already unbiased)
|
||||
PrintArray(TransposedMat([range, List(v, apply), List(w, apply)]));
|
||||
# [ [ 2, 499991, 499041 ],
|
||||
# [ 3, 333310, 500044 ],
|
||||
# [ 4, 249851, 500663 ],
|
||||
# [ 5, 200532, 500448 ],
|
||||
# [ 6, 166746, 499859 ] ]
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
const samples = 1e6
|
||||
|
||||
func main() {
|
||||
fmt.Println("Generator 1 count 0 count % 1 count")
|
||||
for n := 3; n <= 6; n++ {
|
||||
// function randN, per task description
|
||||
randN := func() int {
|
||||
if rand.Intn(n) == 0 {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
var b [2]int
|
||||
for x := 0; x < samples; x++ {
|
||||
b[randN()]++
|
||||
}
|
||||
fmt.Printf("randN(%d) %7d %7d %5.2f%%\n",
|
||||
n, b[1], b[0], float64(b[1])*100/samples)
|
||||
|
||||
// function unbiased, per task description
|
||||
unbiased := func() (b int) {
|
||||
for b = randN(); b == randN(); b = randN() {
|
||||
}
|
||||
return
|
||||
}
|
||||
var u [2]int
|
||||
for x := 0; x < samples; x++ {
|
||||
u[unbiased()]++
|
||||
}
|
||||
fmt.Printf("unbiased %7d %7d %5.2f%%\n",
|
||||
u[1], u[0], float64(u[1])*100/samples)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
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)]
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
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
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
main = forM_ [3..6] showCounts
|
||||
where
|
||||
showCounts b = do
|
||||
r1 <- counts (randN b)
|
||||
r2 <- counts (unbiased (randN b))
|
||||
printf "n = %d biased: %d%% unbiased: %d%%\n" b r1 r2
|
||||
|
||||
counts g = (`div` 100) . length . filter (== 1) <$> replicateM 10000 g
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
procedure main(A)
|
||||
iters := \A[1] | 10000
|
||||
write("ratios of 0 to 1 from ",iters," trials:")
|
||||
every n := 3 to 6 do {
|
||||
results_randN := table(0)
|
||||
results_unbiased := table(0)
|
||||
every 1 to iters do {
|
||||
results_randN[randN(n)] +:= 1
|
||||
results_unbiased[unbiased(n)] +:= 1
|
||||
}
|
||||
showResults(n, "randN", results_randN)
|
||||
showResults(n, "unbiased", results_unbiased)
|
||||
}
|
||||
end
|
||||
|
||||
procedure showResults(n, s, t)
|
||||
write(n," ",left(s,9),":",t[0],"/",t[1]," = ",t[0]/real(t[1]))
|
||||
end
|
||||
|
||||
procedure unbiased(n)
|
||||
repeat {
|
||||
n1 := randN(n)
|
||||
n2 := randN(n)
|
||||
if n1 ~= n2 then suspend n1
|
||||
}
|
||||
end
|
||||
|
||||
procedure randN(n)
|
||||
repeat suspend if 1 = ?n then 1 else 0
|
||||
end
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
randN=: 0 = ?
|
||||
unbiased=: i.@# { ::$: 2 | 0 3 -.~ _2 #.\ 4&* randN@# ]
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
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
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
+/randN 100#3
|
||||
30
|
||||
+/randN 100#4
|
||||
20
|
||||
+/randN 100#5
|
||||
18
|
||||
+/randN 100#6
|
||||
18
|
||||
+/unbiased 100#3
|
||||
49
|
||||
+/unbiased 100#4
|
||||
46
|
||||
+/unbiased 100#5
|
||||
49
|
||||
+/unbiased 100#6
|
||||
47
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
public class Bias {
|
||||
public static boolean biased(int n) {
|
||||
return Math.random() < 1.0 / n;
|
||||
}
|
||||
|
||||
public static boolean unbiased(int n) {
|
||||
boolean a, b;
|
||||
do {
|
||||
a = biased(n);
|
||||
b = biased(n);
|
||||
} while (a == b);
|
||||
return a;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int M = 50000;
|
||||
for (int n = 3; n < 7; n++) {
|
||||
int c1 = 0, c2 = 0;
|
||||
for (int i = 0; i < M; i++) {
|
||||
c1 += biased(n) ? 1 : 0;
|
||||
c2 += unbiased(n) ? 1 : 0;
|
||||
}
|
||||
System.out.format("%d: %2.2f%% %2.2f%%\n",
|
||||
n, 100.0*c1/M, 100.0*c2/M);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
### 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)
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
using Printf
|
||||
|
||||
randN(N) = () -> rand(1:N) == 1 ? 1 : 0
|
||||
function unbiased(biased::Function)
|
||||
this, that = biased(), biased()
|
||||
while this == that this, that = biased(), biased() end
|
||||
return this
|
||||
end
|
||||
|
||||
@printf "%2s | %10s | %5s | %5s | %8s" "N" "bias./unb." "1s" "0s" "pct ratio"
|
||||
const nrep = 10000
|
||||
for N in 3:6
|
||||
biased = randN(N)
|
||||
|
||||
v = collect(biased() for __ in 1:nrep)
|
||||
v1, v0 = count(v .== 1), count(v .== 0)
|
||||
@printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "biased", v1, v0, 100 * v1 / nrep)
|
||||
|
||||
v = collect(unbiased(biased) for __ in 1:nrep)
|
||||
v1, v0 = count(v .== 1), count(v .== 0)
|
||||
@printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "unbiased", v1, v0, 100 * v1 / nrep)
|
||||
end
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
// version 1.1.2
|
||||
|
||||
fun biased(n: Int) = Math.random() < 1.0 / n
|
||||
|
||||
fun unbiased(n: Int): Boolean {
|
||||
var a: Boolean
|
||||
var b: Boolean
|
||||
do {
|
||||
a = biased(n)
|
||||
b = biased(n)
|
||||
}
|
||||
while (a == b)
|
||||
return a
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val m = 50_000
|
||||
val f = "%d: %2.2f%% %2.2f%%"
|
||||
for (n in 3..6) {
|
||||
var c1 = 0
|
||||
var c2 = 0
|
||||
for (i in 0 until m) {
|
||||
if (biased(n)) c1++
|
||||
if (unbiased(n)) c2++
|
||||
}
|
||||
println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
local function randN(n)
|
||||
return function()
|
||||
if math.random() < 1/n then return 1 else return 0 end
|
||||
end
|
||||
end
|
||||
|
||||
local function unbiased(n)
|
||||
local biased = randN (n)
|
||||
return function()
|
||||
local a, b = biased(), biased()
|
||||
while a==b do
|
||||
a, b = biased(), biased()
|
||||
end
|
||||
return a
|
||||
end
|
||||
end
|
||||
|
||||
local function demonstrate (samples)
|
||||
for n = 3, 6 do
|
||||
biased = randN(n)
|
||||
unbias = unbiased(n)
|
||||
local bcounts = {[0]=0,[1]=0}
|
||||
local ucounts = {[0]=0,[1]=0}
|
||||
for i=1, samples do
|
||||
local bnum = biased()
|
||||
local unum = unbias()
|
||||
bcounts[bnum] = bcounts[bnum]+1
|
||||
ucounts[unum] = ucounts[unum]+1
|
||||
end
|
||||
print(string.format("N = %d",n),
|
||||
"# 0", "# 1",
|
||||
"% 0", "% 1")
|
||||
print("biased", bcounts[0], bcounts[1],
|
||||
bcounts[0] / samples * 100,
|
||||
bcounts[1] / samples * 100)
|
||||
print("unbias", ucounts[0], ucounts[1],
|
||||
ucounts[0] / samples * 100,
|
||||
ucounts[1] / samples * 100)
|
||||
end
|
||||
end
|
||||
|
||||
demonstrate(100000)
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
rand[bias_, n_] := 1 - Unitize@RandomInteger[bias - 1, n]
|
||||
unbiased[bias_, n_] := DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]]
|
||||
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"}}]
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
/* NetRexx */
|
||||
options replace format comments java crossref symbols binary
|
||||
|
||||
runSample(arg)
|
||||
return
|
||||
|
||||
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
method biased(n = int) public static returns boolean
|
||||
return Math.random() < 1.0 / n
|
||||
|
||||
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
method unbiased(n = int) public static returns boolean
|
||||
a = boolean
|
||||
b = boolean
|
||||
loop until a \= b
|
||||
a = biased(n)
|
||||
b = biased(n)
|
||||
end
|
||||
return a
|
||||
|
||||
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
method runSample(arg) private static
|
||||
parse arg Mx .
|
||||
if Mx.length <= 0 then Mx = 50000
|
||||
M = int Mx
|
||||
loop n = int 3 to 6
|
||||
c1 = int 0
|
||||
c2 = int 0
|
||||
loop for M
|
||||
if biased(n) then c1 = c1 + 1
|
||||
if unbiased(n) then c2 = c2 + 1
|
||||
end
|
||||
say Rexx(n).right(3)':' Rexx(100.0 * c1 / M).format(6, 2)'%' Rexx(100.0 * c2 / M).format(6, 2)'%'
|
||||
end n
|
||||
return
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import random, sequtils, strformat
|
||||
|
||||
type randProc = proc: range[0..1]
|
||||
|
||||
randomize()
|
||||
|
||||
proc randN(n: Positive): randProc =
|
||||
result = proc: range[0..1] = ord(rand(n) == 0)
|
||||
|
||||
proc unbiased(biased: randProc): range[0..1] =
|
||||
result = biased()
|
||||
var that = biased()
|
||||
while result == that:
|
||||
result = biased()
|
||||
that = biased()
|
||||
|
||||
for n in 3..6:
|
||||
var biased = randN(n)
|
||||
var v = newSeqWith(1_000_000, biased())
|
||||
var cnt0, cnt1 = 0
|
||||
for x in v:
|
||||
if x == 0: inc cnt0 else: inc cnt1
|
||||
echo &"Biased({n}) → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"
|
||||
|
||||
v = newSeqWith(1_000_000, unbiased(biased))
|
||||
cnt0 = 0
|
||||
cnt1 = 0
|
||||
for x in v:
|
||||
if x == 0: inc cnt0 else: inc cnt1
|
||||
echo &"Unbiased → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
let randN n =
|
||||
if Random.int n = 0 then 1 else 0
|
||||
|
||||
let rec unbiased n =
|
||||
let a = randN n in
|
||||
if a <> randN n then a else unbiased n
|
||||
|
||||
let () =
|
||||
Random.self_init();
|
||||
let n = 50_000 in
|
||||
for b = 3 to 6 do
|
||||
let cb = ref 0 in
|
||||
let cu = ref 0 in
|
||||
for i = 1 to n do
|
||||
cb := !cb + (randN b);
|
||||
cu := !cu + (unbiased b);
|
||||
done;
|
||||
Printf.printf "%d: %5.2f%% %5.2f%%\n"
|
||||
b (100.0 *. float !cb /. float n) (100.0 *. float !cu /. float n)
|
||||
done
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
randN(N)=!random(N);
|
||||
unbiased(N)={
|
||||
my(a,b);
|
||||
while(1,
|
||||
a=randN(N);
|
||||
b=randN(N);
|
||||
if(a!=b, return(a))
|
||||
)
|
||||
};
|
||||
for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n))))
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
test: procedure options (main); /* 20 Nov. 2012 */
|
||||
|
||||
randN: procedure(N) returns (bit (1));
|
||||
declare N fixed (1);
|
||||
declare random builtin;
|
||||
declare r fixed (2) external initial (-1);
|
||||
if r >= 0 then do; r = r-1; return ('0'b); end;
|
||||
r = random()*2*N;
|
||||
return ('1'b);
|
||||
end randN;
|
||||
|
||||
random: procedure returns (bit(1));
|
||||
declare (r1, r2) bit (1);
|
||||
do until (r1 ^= r2);
|
||||
r1 = randN(N); r2 = randN(N);
|
||||
end;
|
||||
return (r1);
|
||||
end random;
|
||||
|
||||
declare (biasedrn, unbiasedrn) (100) bit (1);
|
||||
declare N fixed (1);
|
||||
|
||||
put ('N Biased Unbiased (tally of 100 random numbers)');
|
||||
do N = 3 to 6;
|
||||
biasedrn = randN(N); unbiasedrn = random;
|
||||
put skip edit (N, sum(biasedrn), sum(unbiasedrn)) (F(1), 2 F(10));
|
||||
end;
|
||||
|
||||
end test;
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
sub randn {
|
||||
my $n = shift;
|
||||
return int(rand($n) / ($n - 1));
|
||||
}
|
||||
|
||||
for my $n (3 .. 6) {
|
||||
print "Bias $n: ";
|
||||
my (@raw, @fixed);
|
||||
for (1 .. 10000) {
|
||||
my $x = randn($n);
|
||||
$raw[$x]++;
|
||||
$fixed[$x]++ if randn($n) != $x
|
||||
}
|
||||
print "@raw, ";
|
||||
printf("%3g+-%.3g%%\tfixed: ", $raw[0]/100,
|
||||
100 * sqrt($raw[0] * $raw[1]) / ($raw[0] + $raw[1])**1.5);
|
||||
print "@fixed, ";
|
||||
printf("%3g+-%.3g%%\n", 100*$fixed[0]/($fixed[0] + $fixed[1]),
|
||||
100 * sqrt($fixed[0] * $fixed[1]) / ($fixed[0] + $fixed[1])**1.5);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
(phixonline)-->
|
||||
<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;">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>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<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>
|
||||
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
|
||||
<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>
|
||||
<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>
|
||||
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<span style="color: #008080;">constant</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100000</span>
|
||||
<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>
|
||||
<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>
|
||||
<span style="color: #000000;">cu</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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>
|
||||
<!--
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
(de randN (N)
|
||||
(if (= 1 (rand 1 N)) 1 0) )
|
||||
|
||||
(de unbiased (N)
|
||||
(use (A B)
|
||||
(while
|
||||
(=
|
||||
(setq A (randN N))
|
||||
(setq B (randN N)) ) )
|
||||
A ) )
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
(for N (range 3 6)
|
||||
(tab (2 1 7 2 7 2)
|
||||
N ":"
|
||||
(format
|
||||
(let S 0 (do 10000 (inc 'S (randN N))))
|
||||
2 )
|
||||
"%"
|
||||
(format
|
||||
(let S 0 (do 10000 (inc 'S (unbiased N))))
|
||||
2 )
|
||||
"%" ) )
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
function randN ( [int]$N )
|
||||
{
|
||||
[int]( ( Get-Random -Maximum $N ) -eq 0 )
|
||||
}
|
||||
|
||||
function unbiased ( [int]$N )
|
||||
{
|
||||
do {
|
||||
$X = randN $N
|
||||
$Y = randN $N
|
||||
}
|
||||
While ( $X -eq $Y )
|
||||
|
||||
return $X
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
$Tests = 1000
|
||||
ForEach ( $N in 3..6 )
|
||||
{
|
||||
$Biased = 0
|
||||
$Unbiased = 0
|
||||
|
||||
ForEach ( $Test in 1..$Tests )
|
||||
{
|
||||
$Biased += randN $N
|
||||
$Unbiased += unbiased $N
|
||||
}
|
||||
[pscustomobject]@{ N = $N
|
||||
"Biased Ones out of $Test" = $Biased
|
||||
"Unbiased Ones out of $Test" = $Unbiased }
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
Procedure biased(n)
|
||||
If Random(n) <> 1
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
ProcedureReturn 1
|
||||
EndProcedure
|
||||
|
||||
Procedure unbiased(n)
|
||||
Protected a, b
|
||||
Repeat
|
||||
a = biased(n)
|
||||
b = biased(n)
|
||||
Until a <> b
|
||||
ProcedureReturn a
|
||||
EndProcedure
|
||||
|
||||
#count = 100000
|
||||
|
||||
Define n, m, output.s
|
||||
For n = 3 To 6
|
||||
Dim b_count(1)
|
||||
Dim u_count(1)
|
||||
For m = 1 To #count
|
||||
x = biased(n)
|
||||
b_count(x) + 1
|
||||
x = unbiased(n)
|
||||
u_count(x) + 1
|
||||
Next
|
||||
output + "N = " + Str(n) + #LF$
|
||||
output + " biased =>" + #tab$ + "#0=" + Str(b_count(0)) + #tab$ + "#1=" +Str(b_count(1))
|
||||
output + #tab$ + " ratio=" + StrF(b_count(1) / #count * 100, 2) + "%" + #LF$
|
||||
output + " unbiased =>" + #tab$ + "#0=" + Str(u_count(0)) + #tab$ + "#1=" + Str(u_count(1))
|
||||
output + #tab$ + " ratio=" + StrF(u_count(1) / #count * 100, 2) + "%" + #LF$
|
||||
Next
|
||||
MessageRequester("Biased and Unbiased random number results", output)
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
from __future__ import print_function
|
||||
import random
|
||||
|
||||
def randN(N):
|
||||
" 1,0 random generator factory with 1 appearing 1/N'th of the time"
|
||||
return lambda: random.randrange(N) == 0
|
||||
|
||||
def unbiased(biased):
|
||||
'uses a biased() generator of 1 or 0, to create an unbiased one'
|
||||
this, that = biased(), biased()
|
||||
while this == that: # Loop until 10 or 01
|
||||
this, that = biased(), biased()
|
||||
return this # return the first
|
||||
|
||||
if __name__ == '__main__':
|
||||
from collections import namedtuple
|
||||
|
||||
Stats = namedtuple('Stats', 'count1 count0 percent')
|
||||
|
||||
for N in range(3, 7):
|
||||
biased = randN(N)
|
||||
v = [biased() for x in range(1000000)]
|
||||
v1, v0 = v.count(1), v.count(0)
|
||||
print ( "Biased(%i) = %r" % (N, Stats(v1, v0, 100. * v1/(v1 + v0))) )
|
||||
|
||||
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)), ) )
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
$ "bigrat.qky" loadfile
|
||||
|
||||
[ random 0 = ] is randN ( n --> n )
|
||||
|
||||
[ dup randN
|
||||
over randN
|
||||
2dup = iff
|
||||
2drop again
|
||||
drop nip ] is unbias ( n --> n )
|
||||
|
||||
[ dup echo say " biased --> "
|
||||
0
|
||||
1000000 times
|
||||
[ over randN if 1+ ]
|
||||
nip 1000000 6 point$ echo$ ] is showbias ( n --> )
|
||||
|
||||
[ dup echo say " unbiased --> "
|
||||
0
|
||||
1000000 times
|
||||
[ over unbias if 1+ ]
|
||||
nip 1000000 6 point$ echo$ ] is showunbias ( n --> )
|
||||
|
||||
' [ 3 4 5 6 ]
|
||||
witheach
|
||||
[ dup cr
|
||||
showbias cr
|
||||
showunbias cr ]
|
||||
11
Task/Unbias-a-random-generator/R/unbias-a-random-generator.r
Normal file
11
Task/Unbias-a-random-generator/R/unbias-a-random-generator.r
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
randN = function(N) sample.int(N, 1) == 1
|
||||
|
||||
unbiased = function(f)
|
||||
{while ((x <- f()) == f()) {}
|
||||
x}
|
||||
|
||||
samples = 10000
|
||||
print(t(round(d = 2, sapply(3:6, function(N) c(
|
||||
N = N,
|
||||
biased = mean(replicate(samples, randN(N))),
|
||||
unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
/*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.*/
|
||||
if R=='' | R=="," then R=6 /*R: the high number for the range. */
|
||||
if datatype(seed, 'W') then call random ,,seed /*Specified? Then use for RANDOM seed.*/
|
||||
dash='─'; @b="biased"; @ub='un'@b /*literals for the SAY column headers. */
|
||||
say left('',5) ctr("N",5) ctr(@b) ctr(@b'%') ctr(@ub) ctr(@ub"%") ctr('samples')
|
||||
dash=
|
||||
do N=3 to R; b=0; u=0
|
||||
do j=1 for #; b=b + randN(N); u=u + unbiased()
|
||||
end /*j*/
|
||||
say left('', 5) ctr(N, 5) ctr(b) pct(b) ctr(u) pct(u) ctr(#)
|
||||
end /*N*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
ctr: return center( arg(1), word(arg(2) 12, 1), left(dash, 1)) /*show hdr│numbers.*/
|
||||
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*/
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
#lang racket
|
||||
;; Using boolean #t/#f instead of 1/0
|
||||
(define ((randN n)) (zero? (random n)))
|
||||
(define ((unbiased biased))
|
||||
(let loop () (let ([r (biased)]) (if (eq? r (biased)) (loop) r))))
|
||||
|
||||
;; Counts
|
||||
(define N 1000000)
|
||||
(for ([n (in-range 3 7)])
|
||||
(define (try% R) (round (/ (for/sum ([i N]) (if (R) 1 0)) N 1/100)))
|
||||
(define biased (randN n))
|
||||
(printf "Count: ~a => Biased: ~a%; Unbiased: ~a%.\n"
|
||||
n (try% biased) (try% (unbiased biased))))
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
sub randN ( $n where 3..6 ) {
|
||||
return ( $n.rand / ($n - 1) ).Int;
|
||||
}
|
||||
|
||||
sub unbiased ( $n where 3..6 ) {
|
||||
my $n1;
|
||||
repeat { $n1 = randN($n) } until $n1 != randN($n);
|
||||
return $n1;
|
||||
}
|
||||
|
||||
my $iterations = 1000;
|
||||
for 3 .. 6 -> $n {
|
||||
my ( @raw, @fixed );
|
||||
for ^$iterations {
|
||||
@raw[ randN($n) ]++;
|
||||
@fixed[ unbiased($n) ]++;
|
||||
}
|
||||
printf "N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
|
||||
$n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
for n = 3 to 6
|
||||
biased = 0
|
||||
unb = 0
|
||||
for i = 1 to 10000
|
||||
biased += randN(n)
|
||||
unb += unbiased(n)
|
||||
next
|
||||
see "N = " + n + " : biased = " + biased/100 + "%, unbiased = " + unb/100 + "%" + nl
|
||||
next
|
||||
|
||||
func unbiased nr
|
||||
while 1
|
||||
a = randN(nr)
|
||||
if a != randN(nr) return a ok
|
||||
end
|
||||
|
||||
func randN m
|
||||
m = (random(m) = 1)
|
||||
return m
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
def rand_n(bias)
|
||||
rand(bias) == 0 ? 1 : 0
|
||||
end
|
||||
|
||||
def unbiased(bias)
|
||||
a, b = rand_n(bias), rand_n(bias) until a != b #loop until a and b are 0,1 or 1,0
|
||||
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) # counter will respond with 0 when key is not known
|
||||
runs.times do
|
||||
counter[:biased] += 1 if rand_n(bias) == 1 #the first time, counter has no key for :biased, so it will respond 0
|
||||
counter[:unbiased] += 1 if unbiased(bias) == 1
|
||||
end
|
||||
counter[:bias] = bias
|
||||
puts counter.values_at(*keys).join("\t")
|
||||
end
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
#![feature(inclusive_range_syntax)]
|
||||
|
||||
extern crate rand;
|
||||
|
||||
use rand::Rng;
|
||||
|
||||
fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize {
|
||||
rng.gen_weighted_bool(n) as usize // maps `false` to 0 and `true` to 1
|
||||
}
|
||||
|
||||
fn unbiased<R: Rng>(rng: &mut R, n: u32) -> usize {
|
||||
let mut bit = rand_n(rng, n);
|
||||
while bit == rand_n(rng, n) {
|
||||
bit = rand_n(rng, n);
|
||||
}
|
||||
bit
|
||||
}
|
||||
|
||||
fn main() {
|
||||
const SAMPLES: usize = 100_000;
|
||||
let mut rng = rand::weak_rng();
|
||||
|
||||
println!(" Bias rand_n unbiased");
|
||||
for n in 3..=6 {
|
||||
let mut count_biased = 0;
|
||||
let mut count_unbiased = 0;
|
||||
for _ in 0..SAMPLES {
|
||||
count_biased += rand_n(&mut rng, n);
|
||||
count_unbiased += unbiased(&mut rng, n);
|
||||
}
|
||||
|
||||
let b_percentage = 100.0 * count_biased as f64 / SAMPLES as f64;
|
||||
let ub_percentage = 100.0 * count_unbiased as f64 / SAMPLES as f64;
|
||||
println!(
|
||||
"bias {}: {:0.2}% {:0.2}%",
|
||||
n, b_percentage, ub_percentage
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
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 }
|
||||
|
||||
for( i <- (3 until 7) ) println {
|
||||
|
||||
val m = 50000
|
||||
var c1,c2 = 0
|
||||
|
||||
(0 until m) foreach { j => if( biased(i) ) c1 += 1; if( unbiased(i) ) c2 += 1 }
|
||||
|
||||
"%d: %2.2f%% %2.2f%%".format(i, 100.0*c1/m, 100.0*c2/m)
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
$ include "seed7_05.s7i";
|
||||
include "float.s7i";
|
||||
|
||||
const func integer: randN (in integer: n) is
|
||||
return ord(rand(1, n) = 1);
|
||||
|
||||
const func integer: unbiased (in integer: n) is func
|
||||
result
|
||||
var integer: unbiased is 0;
|
||||
begin
|
||||
repeat
|
||||
unbiased := randN(n);
|
||||
until unbiased <> randN(n);
|
||||
end func;
|
||||
|
||||
const proc: main is func
|
||||
local
|
||||
const integer: tests is 50000;
|
||||
var integer: n is 0;
|
||||
var integer: sumBiased is 0;
|
||||
var integer: sumUnbiased is 0;
|
||||
var integer: count is 0;
|
||||
begin
|
||||
for n range 3 to 6 do
|
||||
sumBiased := 0;
|
||||
sumUnbiased := 0;
|
||||
for count range 1 to tests do
|
||||
sumBiased +:= randN(n);
|
||||
sumUnbiased +:= unbiased(n);
|
||||
end for;
|
||||
writeln(n <& ": " <& flt(100 * sumBiased) / flt(tests) digits 3 lpad 6 <&
|
||||
" " <& flt(100 * sumUnbiased) / flt(tests) digits 3 lpad 6);
|
||||
end for;
|
||||
end func;
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
func randN (n) {
|
||||
n.rand / (n-1) -> int
|
||||
}
|
||||
|
||||
func unbiased(n) {
|
||||
var n1 = nil
|
||||
do { n1 = randN(n) } while (n1 == randN(n))
|
||||
return n1
|
||||
}
|
||||
|
||||
var iterations = 1000
|
||||
|
||||
for n in (3..6) {
|
||||
var raw = []
|
||||
var fixed = []
|
||||
iterations.times {
|
||||
raw[ randN(n) ] := 0 ++
|
||||
fixed[ unbiased(n) ] := 0 ++
|
||||
}
|
||||
printf("N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n",
|
||||
n, [raw, fixed].map {|a| (a.dump, a[1] * 100 / iterations) }...)
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
# 1,0 random generator factory with 1 appearing 1/N'th of the time
|
||||
proc randN n {expr {rand()*$n < 1}}
|
||||
|
||||
# uses a biased generator of 1 or 0, to create an unbiased one
|
||||
proc unbiased {biased} {
|
||||
while 1 {
|
||||
if {[set a [eval $biased]] != [eval $biased]} {return $a}
|
||||
}
|
||||
}
|
||||
|
||||
for {set n 3} {$n <= 6} {incr n} {
|
||||
set biased [list randN $n]
|
||||
for {set i 0;array set c {0 0 1 0}} {$i < 1000000} {incr i} {
|
||||
incr c([eval $biased])
|
||||
}
|
||||
puts [format " biased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \
|
||||
[expr {100.*$c(1)/$i}]]
|
||||
for {set i 0;array set c {0 0 1 0}} {$i < 1000000} {incr i} {
|
||||
incr c([unbiased $biased])
|
||||
}
|
||||
puts [format "unbiased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \
|
||||
[expr {100.*$c(1)/$i}]]
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
Module Module1
|
||||
Dim random As New Random()
|
||||
|
||||
Function RandN(n As Integer) As Boolean
|
||||
Return random.Next(0, n) = 0
|
||||
End Function
|
||||
|
||||
Function Unbiased(n As Integer) As Boolean
|
||||
Dim flip1 As Boolean
|
||||
Dim flip2 As Boolean
|
||||
|
||||
Do
|
||||
flip1 = RandN(n)
|
||||
flip2 = RandN(n)
|
||||
Loop While flip1 = flip2
|
||||
|
||||
Return flip1
|
||||
End Function
|
||||
|
||||
Sub Main()
|
||||
For n = 3 To 6
|
||||
Dim biasedZero = 0
|
||||
Dim biasedOne = 0
|
||||
Dim unbiasedZero = 0
|
||||
Dim unbiasedOne = 0
|
||||
For i = 1 To 100000
|
||||
If RandN(n) Then
|
||||
biasedOne += 1
|
||||
Else
|
||||
biasedZero += 1
|
||||
End If
|
||||
If Unbiased(n) Then
|
||||
unbiasedOne += 1
|
||||
Else
|
||||
unbiasedZero += 1
|
||||
End If
|
||||
Next
|
||||
|
||||
Console.WriteLine("(N = {0}):".PadRight(17) + "# of 0" + vbTab + "# of 1" + vbTab + "% of 0" + vbTab + "% of 1", n)
|
||||
Console.WriteLine("(Biased: {0}):".PadRight(15) + "{0}" + vbTab + "{1}" + vbTab + "{2}" + vbTab + "{3}", biasedZero, biasedOne, biasedZero / 1000, biasedOne / 1000)
|
||||
Console.WriteLine("(UnBiased: {0}):".PadRight(15) + "{0}" + vbTab + "{1}" + vbTab + "{2}" + vbTab + "{3}", unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000)
|
||||
Next
|
||||
End Sub
|
||||
|
||||
End Module
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import "random" for Random
|
||||
import "/fmt" for Fmt
|
||||
|
||||
var rand = Random.new()
|
||||
|
||||
var biased = Fn.new { |n| rand.float() < 1 / n }
|
||||
|
||||
var unbiased = Fn.new { |n|
|
||||
while (true) {
|
||||
var a = biased.call(n)
|
||||
var b = biased.call(n)
|
||||
if (a != b) return a
|
||||
}
|
||||
}
|
||||
|
||||
var m = 50000
|
||||
var f = "$d: $2.2f\% $2.2f\%"
|
||||
for (n in 3..6) {
|
||||
var c1 = 0
|
||||
var c2 = 0
|
||||
for (i in 0...m) {
|
||||
if (biased.call(n)) c1 = c1 + 1
|
||||
if (unbiased.call(n)) c2 = c2 + 1
|
||||
}
|
||||
Fmt.print(f, n, 100 * c1 / m, 100 * c2 / m)
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
fcn randN(N){ (not (0).random(N)).toInt() }
|
||||
fcn unbiased(randN){ while((a:=randN())==randN()){} a }
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
const Z=0d100_000;
|
||||
foreach N in ([3..6]){
|
||||
"%d: biased: %3.2f%%, unbiased: %3.2f%%".fmt(N,
|
||||
(0).reduce(Z,'wrap(s,_){ s+randN(N) },0.0)/Z*100,
|
||||
(0).reduce(Z,'wrap(s,_){ s+unbiased(randN.fp(N)) },0.0)/Z*100)
|
||||
.println();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue