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("%f\n", sample);
22
23    sample = generate_opt_ext(gaussian_ddf, &prng);
24    printf("%f\n", sample);
25
26    // EXAMPLE 2: Poisson distribution from the GNU library (discrete).
27    MAKE_CDF_UINT_P(poisson_cdf, gsl_cdf_poisson_P, 5);
28    MAKE_CDF_UINT_Q(poisson_sf, gsl_cdf_poisson_Q, 5);
29    MAKE_DDF(poisson_ddf, poisson_cdf, poisson_sf);
30
31    sample = generate_opt(poisson_cdf, &prng);
32    printf("%f\n", sample);
33
34    sample = generate_opt_ext(poisson_ddf, &prng);
35    printf("%f\n", sample);
36
37    // EXAMPLE 3: A custom discrete distribution.
38    float P[4] = {0.1, 0.3, 0.5, 0.8};
39    MAKE_CDF_UINT_P(custom_discrete_cdf, cdf_discrete, P, 4);
40    sample = generate_opt(custom_discrete_cdf, &prng);
41    printf("%f\n", sample);
42
43    // EXAMPLE 4: A custom continuous distribution, F(x) = x^2 over [0,1].
44    float custom_continuous_cdf(double x) {
45        if      (x != x)        { return 1.; }       // nan
46        else if (signbit(x))    { return 0; }        // <= -0.0
47        else if (1 <= x)        { return 1; }
48        else                    { return x*x; }
49    }
50    printf("%f\n", generate_opt(custom_continuous_cdf, &prng));
51
52    // EXAMPLE 5: A custom CDF that is a point mass at NaN.
53    float custom_delta_cdf(double x) {
54        return (x != x) ? 1. : 0.;
55    }
56    printf("%f\n", generate_opt(custom_delta_cdf, &prng));
57
58    // Free the random number generator.
59    gsl_rng_free(rng);
60
61}