Fix #132858, Sven Neumann, patch by James Henstridge:
[glib.git] / tests / rand-test.c
blob141883eb86248c5dd734ef1defa910c1da5bbeed
1 #undef G_DISABLE_ASSERT
2 #undef G_LOG_DOMAIN
4 #include <glib.h>
6 /* Outputs tested against the reference implementation mt19937ar.c from
7 http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html */
9 /* Tests for a simple seed, first number is the seed */
10 const guint32 first_numbers[] =
12 0x7a7a7a7a,
13 0xfdcc2d54,
14 0x3a279ceb,
15 0xc4d39c33,
16 0xf31895cd,
17 0x46ca0afc,
18 0x3f5484ff,
19 0x54bc9557,
20 0xed2c24b1,
21 0x84062503,
22 0x8f6404b3,
23 0x599a94b3,
24 0xe46d03d5,
25 0x310beb78,
26 0x7bee5d08,
27 0x760d09be,
28 0x59b6e163,
29 0xbf6d16ec,
30 0xcca5fb54,
31 0x5de7259b,
32 0x1696330c,
35 /* array seed */
36 const guint32 seed_array[] =
38 0x6553375f,
39 0xd6b8d43b,
40 0xa1e7667f,
41 0x2b10117c
44 /* tests for the array seed */
45 const guint32 array_outputs[] =
47 0xc22b7dc3,
48 0xfdecb8ae,
49 0xb4af0738,
50 0x516bc6e1,
51 0x7e372e91,
52 0x2d38ff80,
53 0x6096494a,
54 0xd162d5a8,
55 0x3c0aaa0d,
56 0x10e736ae
59 const gint length = sizeof (first_numbers) / sizeof (first_numbers[0]);
60 const gint seed_length = sizeof (seed_array) / sizeof (seed_array[0]);
61 const gint array_length = sizeof (array_outputs) / sizeof (array_outputs[0]);
63 int main()
65 guint n;
66 guint ones;
67 double proportion;
69 GRand* rand = g_rand_new_with_seed (first_numbers[0]);
70 GRand* copy;
72 for (n = 1; n < length; n++)
73 g_assert (first_numbers[n] == g_rand_int (rand));
75 g_rand_set_seed (rand, 2);
76 g_rand_set_seed_array (rand, seed_array, seed_length);
78 for (n = 0; n < array_length; n++)
79 g_assert (array_outputs[n] == g_rand_int (rand));
81 copy = g_rand_copy (rand);
82 for (n = 0; n < 100; n++)
83 g_assert (g_rand_int (copy) == g_rand_int (rand));
85 for (n = 1; n < 100000; n++)
87 gint32 i;
88 gdouble d;
89 gboolean b;
91 i = g_rand_int_range (rand, 8,16);
92 g_assert (i >= 8 && i < 16);
94 i = g_random_int_range (8,16);
95 g_assert (i >= 8 && i < 16);
97 d = g_rand_double (rand);
98 g_assert (d >= 0 && d < 1);
100 d = g_random_double ();
101 g_assert (d >= 0 && d < 1);
103 d = g_rand_double_range (rand, -8, 32);
104 g_assert (d >= -8 && d < 32);
106 d = g_random_double_range (-8, 32);
107 g_assert (d >= -8 && d < 32);
109 b = g_random_boolean ();
110 g_assert (b == TRUE || b == FALSE);
112 b = g_rand_boolean (rand);
113 g_assert (b == TRUE || b == FALSE);
116 /* Statistical sanity check, count the number of ones
117 * when getting random numbers in range [0,3) and see
118 * that it must be semi-close to 0.25 with a VERY large
119 * probability */
120 ones = 0;
121 for (n = 1; n < 100000; n++)
123 if (g_random_int_range (0, 4) == 1)
124 ones ++;
126 proportion = (double)ones / (double)100000;
127 /* 0.025 is overkill, but should suffice to test for some unreasonability */
128 g_assert (ABS (proportion - 0.25) < 0.025);
130 g_rand_free (rand);
131 g_rand_free (copy);
133 return 0;