summaryrefslogtreecommitdiffhomepage
path: root/examples/random.c
blob: c923debd30c62aa13221a1b573d48c9b9834f972 (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
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stc/crandom.h>
#include <stc/cstr.h>

int main()
{
    enum {R = 30};
    const size_t N = 1000000000;
    uint64_t seed = 1234; // time(NULL);
    stc64_t rng = stc64_init(seed);

    uint64_t sum = 0;

    stc64_normalf_t dist2 = stc64_normalf_init(R / 2.0, R / 6.0);
    size_t N2 = 10000000;
    int hist[R] = {0};
    sum = 0;
    c_forrange (N2)  {
        int n = round((stc64_normalf(&rng, &dist2) + 0.5));
        sum += n;
        if (n >= 0 && n < R) ++hist[n];
    }
    cstr_t bar = cstr_inits;
    c_forrange (i, int, R)  {
        cstr_resize(&bar, hist[i] * 25ull * R / N2, '*');
        printf("%3d %s\n", i, bar.str);
    }

    clock_t diff, before;    

    sum = 0;
    before = clock();    
    c_forrange (N)  {
        sum += stc64_rand(&rng);
    }
    diff = clock() - before;
    printf("random : %f secs, %zu %f\n", (float) diff / CLOCKS_PER_SEC, N, (double) sum / N);

    stc64_uniform_t dist1 = stc64_uniform_init(0, 1000);
    sum = 0;
    before = clock();    
    c_forrange (N)  {
        sum += stc64_uniform(&rng, &dist1);
    }
    diff = clock() - before;
    printf("uniform: %f secs, %zu %f\n", (float) diff / CLOCKS_PER_SEC, N, (double) sum / N);

    cstr_del(&bar);
}