Unbias a random generator: Difference between revisions

Content deleted Content added
use proper range
Updated D code
Line 292: Line 292:
<lang d>import std.stdio, std.random;
<lang d>import std.stdio, std.random;


bool biased(int n) {
bool biased(in int n) /*nothrow*/ {
return uniform(0.0, 1.0) < (1.0 / n);
return uniform(0.0, 1.0) < (1.0 / n);
}
}


bool unbiased(int n) {
bool unbiased(in int n) /*nothrow*/ {
bool a, b;
while (true) {
immutable bool a = biased(n);
do {
a = biased(n);
if (a != biased(n))
b = biased(n);
return a;
} while (a == b);
}
return a;
}
}


void main() {
void main() {
int M = 50_000;
enum int M = 20_000_000;
foreach (n; 3 .. 7) {
foreach (n; 3 .. 7) {
int c1, c2;
int a1, a2; // accumulators
foreach (i; 0 .. M) {
foreach (i; 0 .. M) {
c1 += biased(n);
a1 += biased(n);
c2 += unbiased(n);
a2 += unbiased(n);
}
}
writefln("%d: %2.2f%% %2.2f%%", n, 100.0*c1/M, 100.0*c2/M);
writefln("%d: %2.3f%% %2.3f%%", n,
100.0 * a1 / M, 100.0 * a2 / M);
}
}
}</lang>
}</lang>
Output:
Output:
<pre>3: 33.12% 50.15%
<pre>3: 33.352% 50.002%
4: 25.13% 50.02%
4: 25.006% 49.989%
5: 19.61% 50.01%
5: 19.995% 49.989%
6: 16.70% 49.98%</pre>
6: 16.679% 50.007%</pre>


=={{header|Euphoria}}==
=={{header|Euphoria}}==