summaryrefslogtreecommitdiff
path: root/t/gen-rand.c
blob: b050bd715a6c067ddc349392f9dc909cddeb9d19 (plain)
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
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include "../lib/types.h"
#include "../lib/rand.h"
#include "../log.h"

int main(int argc, char *argv[])
{
	struct frand_state s;
	uint64_t i, start, end, nvalues;
	unsigned long *buckets, index, pass, fail;
	double p, dev, mean, vmin, vmax;

	if (argc < 4) {
		log_err("%s: start end nvalues\n", argv[0]);
		return 1;
	}

	start = strtoul(argv[1], NULL, 10);
	end = strtoul(argv[2], NULL, 10);

	if (start >= end) {
		log_err("%s: start must be smaller than end\n", argv[0]);
		return 1;
	}
	index = 1 + end - start;
	buckets = calloc(index, sizeof(unsigned long));

	nvalues = strtoul(argv[3], NULL, 10);

	init_rand(&s, false);

	for (i = 0; i < nvalues; i++) {
		int v = rand_between(&s, start, end);

		buckets[v - start]++;
	}

	p = 1.0 / index;
	dev = sqrt(nvalues * p * (1.0 - p));
	mean = nvalues * p;
	vmin = mean - dev;
	vmax = mean + dev;

	pass = fail = 0;
	for (i = 0; i < index; i++) {
		if (buckets[i] < vmin || buckets[i] > vmax) {
			printf("FAIL bucket%4lu: val=%8lu (%.1f < %.1f > %.1f)\n", (unsigned long) i + 1, buckets[i], vmin, mean, vmax);
			fail++;
		} else {
			printf("PASS bucket%4lu: val=%8lu (%.1f < %.1f > %.1f)\n", (unsigned long) i + 1, buckets[i], vmin, mean, vmax);
			pass++;
		}
	}

	printf("Passes=%lu, Fail=%lu\n", pass, fail);
	free(buckets);
	return 0;
}