user130375
user130375

Reputation:

Calculation of Poisson distribution in C

I need a C function to calculate Poisson distribution for values of k up to 720. I need a highly efficient solution.

Upvotes: 3

Views: 15904

Answers (4)

jam spandex
jam spandex

Reputation: 31

I guess this is far too late for the original request, but I think some of the answers miss the point - I don't think he wants to generate random numbers from a distribution, but wants the distribution itself. Here is a function to do this avoiding the calculation of factorials which can become large.

double poisson( int k, double mean ) { 
  double p = std::exp(-mean);
  double f = 1;
  for ( int i=0 ; i<k ; i++ ) f *= mean/(i+1);     
  return p*f;
}

Upvotes: 1

SureshS
SureshS

Reputation: 609

Poisson Random Generator

int poissonRandom(double expectedValue) {
  int n = 0; //counter of iteration
  double limit; 
  double x;  //pseudo random number
  limit = exp(-expectedValue);
  x = rand() / INT_MAX; 
  while (x > limit) {
    n++;
    x *= rand() / INT_MAX;
  }
  return n;
}

I guess I'm pretty late for your urgent demand.

Upvotes: 5

sud03r
sud03r

Reputation: 19769

If you want to calculate it yourself instead of using a library You can calculate it using the formula.. e^k*e^(-lambda)/k!
you can use log(n!) = log(n)+log(n-1!) and dynamic programming

Upvotes: 2

dfa
dfa

Reputation: 116382

give a to try GSL: gsl_ran_poisson_pdf

Upvotes: 8

Related Questions