Example
The following example highlights the essential interface.
1#include <gsl/gsl_rng.h>
2#include <gsl/gsl_cdf.h>
3
4#include "rvg/generate.h"
5#include "rvg/discrete.h"
6
7int main(int argc, char * argv[]) {
8
9 // Prepare the random number generator.
10 gsl_rng * rng = gsl_rng_alloc(gsl_rng_default);
11 struct flip_state prng = make_flip_state(rng);
12
13 double sample;
14
15 // EXAMPLE 1: Gaussian distribution from the GNU library (continuous).
16 MAKE_CDF_P(gaussian_cdf, gsl_cdf_gaussian_P, 1);
17 MAKE_CDF_Q(gaussian_sf, gsl_cdf_gaussian_Q, 1);
18 MAKE_DDF(gaussian_ddf, gaussian_cdf, gaussian_sf);
19
20 sample = generate_opt(gaussian_cdf, &prng);
21 printf("OPT GAUS CDF\t%f\n", sample);
22
23 sample = generate_opt_ext(gaussian_ddf, &prng);
24 printf("OPT GAUS DDF\t%f\n", sample);
25
26 sample = generate_inversion(gaussian_cdf, &prng);
27 printf("INV GAUS CDF\t%f\n", sample);
28
29 sample = generate_inversion_ext(gaussian_ddf, &prng);
30 printf("INV GAUS DDF\t%f\n", sample);
31
32 // EXAMPLE 2: Poisson distribution from the GNU library (discrete).
33 MAKE_CDF_UINT_P(poisson_cdf, gsl_cdf_poisson_P, 5);
34 MAKE_CDF_UINT_Q(poisson_sf, gsl_cdf_poisson_Q, 5);
35 MAKE_DDF(poisson_ddf, poisson_cdf, poisson_sf);
36
37 sample = generate_opt(poisson_cdf, &prng);
38 printf("OPT POIS CDF\t%f\n", sample);
39
40 sample = generate_opt_ext(poisson_ddf, &prng);
41 printf("OPT POIS DDF\t%f\n", sample);
42
43 sample = generate_inversion(poisson_cdf, &prng);
44 printf("INV POIS CDF\t%f\n", sample);
45
46 sample = generate_inversion_ext(poisson_ddf, &prng);
47 printf("INV POIS DDF\t%f\n", sample);
48
49 // EXAMPLE 3: A custom discrete distribution.
50 float P[4] = {0.1, 0.3, 0.5, 0.8};
51 MAKE_CDF_UINT_P(custom_discrete_cdf, cdf_discrete, P, 4);
52 sample = generate_opt(custom_discrete_cdf, &prng);
53 printf("OPT DISCRETE\t%f\n", sample);
54 sample = generate_inversion(custom_discrete_cdf, &prng);
55 printf("INV DISCRETE\t%f\n", sample);
56
57 // EXAMPLE 4: A custom continuous distribution, F(x) = x^2 over [0,1].
58 float custom_continuous_cdf(double x) {
59 if (x != x) { return 1.; } // nan
60 else if (signbit(x)) { return 0; } // <= -0.0
61 else if (1 <= x) { return 1; }
62 else { return x*x; }
63 }
64 printf("OPT X^2\t\t%f\n", generate_opt(custom_continuous_cdf, &prng));
65 printf("INV X^2\t\t%f\n", generate_inversion(custom_continuous_cdf, &prng));
66
67 // EXAMPLE 5: A custom CDF that is a point mass at NaN.
68 float custom_delta_cdf(double x) {
69 return (x != x) ? 1. : 0.;
70 }
71 printf("OPT DELTA\t%f\n", generate_opt(custom_delta_cdf, &prng));
72 printf("INV DELTA\t%f\n", generate_inversion(custom_delta_cdf, &prng));
73
74 // Free the random number generator.
75 gsl_rng_free(rng);
76
77}