Unbias a random generator: Difference between revisions

Content added Content deleted
(→‎{{header|Perl}}: fixed stddev for binomial distr)
Line 7: Line 7:


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.
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.
=={{header|C}}==
<lang C>#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 rand() < 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: %5d %5.3f%% vs %5d %5.3f\n", b,
cb, 100. * cb / n, cu, 100. * cu / n);
}

return 0;
}</lang>output<lang>bias 3: 3309 33.090% vs 4971 49.710
bias 4: 2513 25.130% vs 4943 49.430
bias 5: 1976 19.760% vs 4965 49.650
bias 6: 1674 16.740% vs 5003 50.030</lang>

=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>(defn biased [n]
<lang Clojure>(defn biased [n]