0

I'm new to C++ and I'm using the boost library to generate random variables. I want to generate random variables from a negative binomial distribution.

The first parameter of boost::random::negative_binomial_distribution<int> freq_nb(r, p); has to be an integer. I want to expand that to a real value. Therefore I would like to use a poisson-gamma mixture, but I fail to.

Here's an excerpt from my code:

    int nr_sim = 1000000;
    double mean = 2.0;
    double variance = 15.0;
    double r = mean * mean / (variance - mean);
    double p = mean / variance;
    double beta = (1 - p) / p;

    typedef boost::mt19937 RNGType;
    RNGType rng(5);

    boost::random::gamma_distribution<double> my_gamma(r, beta);
    boost::random::poisson_distribution<int> my_poi(my_gamma(rng));

    int simulated_mean = 0;
    for (int i = 0; i < nr_sim; i++) {
        simulated_mean += my_poi(rng);
    }
    double my_result = (double)simulated_mean / (double)nr_sim;

With my_result == 0.5 there is definitly something wrong. Is it my_poi(my_gamma(rng))? If so, what is the correct way to solve that problem?

dan
  • 25
  • 6
  • I'm not familiar with these distributions, but just a few questions from my side: Why do you want to expand the first parameter of boost::random::negative_binomial_distribution to a real value? The first parameter is the number of successes, so does a real value make sense here? simulated_mean is an integer. Does my_poi() always returns an integer? If not, you will have some rounding issues there. You could also decrease the number of simulations nr_sim and print out some values and check if they are realistic. – CodingWithMagga Jun 27 '22 at 13:01
  • The "number of successes"-interpretation can only be done when the first parameter is an integer. But you can generalize the neg. bin distribution by making the first parameter real. In my example, `r = 0.34`. If you set `r = 0`, then the simulated mean would be `0`. If you set `r = 1`, then the simulated mean would equal `6`, but it should be approx. `2`. Poisson distribution is a discrete distribution. Therefore a sampled poisson random variable is always an integer. – dan Jun 27 '22 at 13:25
  • I think the issue lies in your random number generation. The number in `RNGType rng(5);` seems to have a high impact on the outcome. Using `my_poi(my_gamma(rng))` depends hard on the first generated values from `rng`. When adding this line to the loop, I always get results around 1.8 tills 2.0. – CodingWithMagga Jun 27 '22 at 14:04

0 Answers0