add related commit to raise-race test
[libc-test] / src / functional / random.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "test.h"
4
5 /* naive statistical checks */
6
7 /* error p ~ 1.6e-6 */
8 static int chkmissing(long *x)
9 {
10         int d[8] = {0};
11         int i;
12         for (i = 0; i < 100; i++)
13                 d[x[i]%8]++;
14         for (i = 0; i < 8; i++)
15                 if (d[i]==0)
16                         return 1;
17         return 0;
18 }
19
20 /* error p ~ 4e-6 */
21 static int chkrepeat(long *x)
22 {
23         int i, j;
24         for (i = 0; i < 100; i++)
25                 for (j = 0; j < i; j++)
26                         if (x[i] == x[j])
27                                 return 1;
28         return 0;
29 }
30
31 /* error p ~ 1e-6 */
32 static unsigned orx;
33 static int chkones(long *x)
34 {
35         int i;
36         orx = 0;
37         for (i = 0; i < 20; i++)
38                 orx |= x[i];
39         return orx != 0x7fffffff;
40 }
41
42 void checkseed(unsigned seed, long *x)
43 {
44         int i;
45         srandom(seed);
46         for (i = 0; i < 100; i++)
47                 x[i] = random();
48         if (chkmissing(x))
49                 t_error("weak seed %d, missing pattern in low bits\n", seed);
50         if (chkrepeat(x))
51                 t_error("weak seed %d, exact repeats\n", seed);
52         if (chkones(x))
53                 t_error("weak seed %d, or pattern: 0x%08x\n", seed, orx);
54 }
55
56 int main()
57 {
58         long x[100];
59         long y,z;
60         int i;
61         char state[128];
62         char *p;
63         char *q;
64
65         for (i = 0; i < 100; i++)
66                 x[i] = random();
67         p = initstate(1, state, sizeof state);
68         for (i = 0; i < 100; i++)
69                 if (x[i] != (y = random()))
70                         t_error("initstate(1) is not default: (%d) default: %ld, seed1: %ld\n", i, x[i], y);
71         for (i = 0; i < 10; i++) {
72                 z = random();
73                 q = setstate(p);
74                 if (z != (y = random()))
75                         t_error("setstate failed (%d) orig: %ld, reset: %ld\n", i, z, y);
76                 p = setstate(q);
77         }
78         srandom(1);
79         for (i = 0; i < 100; i++)
80                 if (x[i] != (y = random()))
81                         t_error("srandom(1) is not default: (%d) default: %ld, seed1: %ld\n", i, x[i], y);
82         checkseed(0x7fffffff, x);
83         for (i = 0; i < 10; i++)
84                 checkseed(i, x);
85         return t_status;
86 }