Repository navigation
Expand file tree
/
Copy pathalgC3.c
More file actions
114 lines (105 loc) · 2.71 KB
/
Copy pathalgC3.c
File metadata and controls
114 lines (105 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/******************************************************
Robert Jones
Feb 2, 1997
CSci 726
Algorithm C.3
******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "rvms.h"
#include "rngs.h"
#include "sort.h"
#define n 7200L
#define k 6
#define alpha 0.05
#define max(x,y) (((x) > (y)) ? (x) : (y))
int main(void)
{
long x, i; /* indices */
long t; /* rng stream */
long *o; /* histogram */
long counter;
long total = 0;
double f;
double u; /* ~Unif(0,1) sample */
double r; /* run length */
double p; /* Pr of run length = x */
double *v; /* chi-square statistic */
double v1, v2;
double diff;
double F; /* theoretic cdf */
double dt; /* KS statistic */
/* allocate memory: o[0..k] is the run-length histogram and v[1..256]
holds one chi-square statistic per stream. (2026: these used to be
allocated with k elements each, overrunning both arrays.) */
o = (long *)calloc(k + 1, sizeof(long));
v = (double *)calloc(256 + 1, sizeof(double));
if (o == nullptr || v == nullptr) {
fprintf(stderr, "Error allocating memory.\n");
free(o);
free(v);
return EXIT_FAILURE;
}
/*
* determine critical values v1 and v2
*/
v1 = idfChisquare(k-1,alpha/2);
v2 = idfChisquare(k-1,1-alpha/2);
printf("\nk = %d, v1 = %g, v2 = %g\n",k,v1,v2);
PlantSeeds(231886580);
/* for each random number stream s */
for (t = 1; t <= 256; t++) {
SelectStream(t-1);
/*
* compute histogram
*/
for (x = 0; x <= k; x++) {
o[x] = 0;
}
counter = 0;
for (i = 1; i <= n; i++) {
x = 0;
r = Random();
counter++;
do {
x += 1;
u = r;
r = Random();
counter++;
} while (r >= u);
if (x > k) {
x = k;
}
o[x] += 1;
}
printf("number of calls to Random = %ld\n",counter);
total += counter;
/*
* compute chi-square statistic
*/
v[t] = 0.0;
f = 1.0;
for (x = 1; x <= k; x++) {
f *= (x+1);
p = x/f;
diff = o[x] - p;
v[t] += diff*diff/(n*p);
}
}
/*
* sort chi-square statistics in increasing order
*/
Sort(v,1,256);
/*
* compute KS statistic
*/
dt = 0.0;
for (i = 1; i <= 256; i++) {
F = cdfChisquare(k,v[i]);
diff = max(fabs(F - (double)(i-1)/t),fabs(F - (double)i/t));
dt = max(diff,dt);
}
printf("\nKS statistic for 256 tests is %g\n",dt);
printf("average number of calls to Random = %g\n",(double)total/256);
}/*end*/