Anonymous user
Verify distribution uniformity/Naive: Difference between revisions
Verify distribution uniformity/Naive (view source)
Revision as of 04:56, 21 July 2011
, 12 years ago→{{header|C}}: replace: remove odd lib dependence
m ({{omit from|GUISS}}) |
(→{{header|C}}: replace: remove odd lib dependence) |
||
Line 58:
=={{header|C}}==
<lang c>#include <stdlib.h>▼
▲#include <stdlib.h>
#include <math.h>
inline int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
while ((r = rand()) >= rand_max);
return r / (rand_max / 5) + 1;
}
inline int rand5_7()
{
int r;
while ((r = rand5() * 5 + rand5()) >= 27);
return r / 3 - 1;
}
/* assumes gen() returns a value from 1 to n */
int check(int (*gen)(), int n, int cnt, double delta) /* delta is relative */
{
int i = cnt, *bins = calloc(sizeof(int), n);
double ratio;
for(i=0; i < n; i++) {▼
while (i--) bins[gen() - 1]++;
ratio = bins[i] * n / (double)cnt - 1;
if (ratio > -delta && ratio < delta) continue;
printf("bin %d out of range: %d (%g%% vs %g%%), ",
i + 1, bins[i], ratio * 100, delta * 100);
break;
}
free(bins);
return i == n;
}
int main()
{
int cnt = 1;
while ((cnt *= 10) <= 1000000) {
return 0;▼
printf("Count = %d: ", cnt);
}</lang>▼
printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n");
}
▲}</lang>output<pre>
Count = 10: bin 1 out of range: 1 (-30% vs 3%), NOT flat
Count = 100: bin 1 out of range: 11 (-23% vs 3%), NOT flat
Count = 1000: bin 1 out of range: 150 (5% vs 3%), NOT flat
Count = 10000: bin 3 out of range: 1477 (3.39% vs 3%), NOT flat
Count = 100000: flat
Count = 1000000: flat
</pre>
=={{header|C++}}==
|