diff options
Diffstat (limited to 'src/distribution.c')
| -rw-r--r-- | src/distribution.c | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/src/distribution.c b/src/distribution.c new file mode 100644 index 0000000..7887ba3 --- /dev/null +++ b/src/distribution.c | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | #define _GNU_SOURCE | ||
| 2 | #include <stdlib.h> | ||
| 3 | #include <assert.h> | ||
| 4 | #include <stdio.h> | ||
| 5 | |||
| 6 | #include "distribution.h" | ||
| 7 | |||
| 8 | void | ||
| 9 | distribution_init (DISTRIBUTION dist, | ||
| 10 | unsigned int n, | ||
| 11 | unsigned int b, | ||
| 12 | unsigned int r, | ||
| 13 | int c) | ||
| 14 | { | ||
| 15 | assert (n > 0); | ||
| 16 | assert (b > 0); | ||
| 17 | assert (r > 0); | ||
| 18 | assert (b + r + c*(n - 1) > 0); | ||
| 19 | |||
| 20 | dist->n = n; | ||
| 21 | dist->b = b; | ||
| 22 | dist->r = r; | ||
| 23 | dist->c = c; | ||
| 24 | dist->p0 = r/(float)(b + r); | ||
| 25 | for (int i = 1; i < n; ++i) { | ||
| 26 | dist->p0 *= (r + i*c)/(float)(b + r + i*c); | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | int | ||
| 31 | distribution_rand (DISTRIBUTION dist) | ||
| 32 | { | ||
| 33 | for (;;) { | ||
| 34 | double p = dist->p0; | ||
| 35 | double r = rand ()/(double) RAND_MAX; | ||
| 36 | // printf ("r = %f, p = %f\n", r, p); | ||
| 37 | unsigned int x = 0; | ||
| 38 | |||
| 39 | while (x < dist->n - 1) { | ||
| 40 | r -= p; | ||
| 41 | if (r < 0) | ||
| 42 | return x; | ||
| 43 | x += 1; | ||
| 44 | p *= ((dist->n - 1 - x) * | ||
| 45 | (dist->b + (x - 1)*dist->c) /(double) | ||
| 46 | (x*(dist->r + (dist->n - x)*dist->c))); | ||
| 47 | // printf ("p = %f\n", p); | ||
| 48 | } // putchar ('\n'); | ||
| 49 | } | ||
| 50 | // return dist->n; | ||
| 51 | } | ||
| 52 | |||
| 53 | double | ||
| 54 | distribution_nrand (DISTRIBUTION dist) | ||
| 55 | { | ||
| 56 | return distribution_rand (dist)/(double) (dist->n - 2); | ||
| 57 | } | ||
