Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating poisson variables in c++

I implemented this function to generate a poisson random variable

typedef long unsigned int luint;
luint poisson(luint lambda) {
    double L = exp(-double(lambda));
    luint k = 0;
    double p = 1;
    do {
        k++;
        p *= mrand.rand();
    } while( p > L);
    return (k-1);
}

where mrand is the MersenneTwister random number generator. I find that, as I increase lambda, the expected distribution is going to be wrong, with a mean that saturates at around 750. Is it due to numerical approximations or did I make any mistakes?

like image 949
Bob Avatar asked Apr 14 '11 02:04

Bob


People also ask

How do you make Poisson?

then N is a random variable distributed according to a Poisson distribution. Generating exponential variates is easily done by using the inverse method. For a uniform random variable U on the unit interval (0,1), the transformation E= -\log(U)/\lambda gives an exponential random variable with mean 1/\lambda.

How do you generate a random number in a Poisson distribution?

r = poissrnd( lambda ) generates random numbers from the Poisson distribution specified by the rate parameter lambda . lambda can be a scalar, vector, matrix, or multidimensional array.

How do you simulate a Poisson process?

Simulating a Poisson process For the given average incidence rate λ, use the inverse-CDF technique to generate inter-arrival times. Generate actual arrival times by constructing a running-sum of the interval arrival times.

How do you create a Poisson distribution?

The Poisson Distribution formula is: P(x; μ) = (e-μ) (μx) / x! Let's say that that x (as in the prime counting function is a very big number, like x = 10100. If you choose a random number that's less than or equal to x, the probability of that number being prime is about 0.43 percent.


1 Answers

If you go the "existing library" route, your compiler may already support the C++11 std::random package. Here is how you use it:

#include <random>
#include <ctime>
#include <iostream>

std::mt19937 mrand(std::time(0));  // seed however you want

typedef long unsigned int luint;

luint poisson(luint lambda)
{
    std::poisson_distribution<luint> d(lambda);
    return d(mrand);
}

int main()
{
    std::cout << poisson(750) << '\n';
    std::poisson_distribution<luint> d(750);
    std::cout << d(mrand) << '\n';
    std::cout << d(mrand) << '\n';
}

I've used it two ways above:

  1. I tried to imitate your existing interface.

  2. If you create a std::poisson_distribution with a mean, it is more efficient to use that distribution over and over for the same mean (as done in main()).

Here is sample output for me:

751
730
779
like image 81
Howard Hinnant Avatar answered Sep 20 '22 10:09

Howard Hinnant