blob: 7887ba3f3c853952a2b64af827aa2e7e1a52f6c5 (
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
|
#define _GNU_SOURCE
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "distribution.h"
void
distribution_init (DISTRIBUTION dist,
unsigned int n,
unsigned int b,
unsigned int r,
int c)
{
assert (n > 0);
assert (b > 0);
assert (r > 0);
assert (b + r + c*(n - 1) > 0);
dist->n = n;
dist->b = b;
dist->r = r;
dist->c = c;
dist->p0 = r/(float)(b + r);
for (int i = 1; i < n; ++i) {
dist->p0 *= (r + i*c)/(float)(b + r + i*c);
}
}
int
distribution_rand (DISTRIBUTION dist)
{
for (;;) {
double p = dist->p0;
double r = rand ()/(double) RAND_MAX;
// printf ("r = %f, p = %f\n", r, p);
unsigned int x = 0;
while (x < dist->n - 1) {
r -= p;
if (r < 0)
return x;
x += 1;
p *= ((dist->n - 1 - x) *
(dist->b + (x - 1)*dist->c) /(double)
(x*(dist->r + (dist->n - x)*dist->c)));
// printf ("p = %f\n", p);
} // putchar ('\n');
}
// return dist->n;
}
double
distribution_nrand (DISTRIBUTION dist)
{
return distribution_rand (dist)/(double) (dist->n - 2);
}
|