# Poisson random number generator

What is the shortest function (implemented in C) that will return a random draw from a Poisson distribution (given the mean or `λ` parameter)?

``````int random_poisson(double lambda);
``````
-
 Why is this question restricted to C? Might be a better fit for SE. – user unknown Nov 8 '11 at 4:37

Taken from the wikipedia article which credits Knuth (and notes that there are implementations with better time performance) this code is a complete program implementing a minimal test scaffold. The code that does the actual work is 169 characters still formatted:

``````#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <string.h>

/* For serious work you need a high quality random number generator
*
* And these macros may need to be adjusted for your system and choice
* of random number engine.
*/
#define GOODRAND random()
#define GOODRANDMAX INT_MAX
#define RANDTYPE long

/* poisson.c
*
* Implementation straight from
* http://en.wikipedia.org/wiki/Poisson_distribution#Generating_Poisson-distributed_random_variables
* which credits Knuth.
*
* Time complexity is O(lambda), which is not optimal.
*/
RANDTYPE poisson(double lambda){
RANDTYPE k=0;
double L=exp(-lambda), p=1;
do {
++k;
p *= GOODRAND/(double)GOODRANDMAX;
} while (p > L);
return --k;
}

/* minimal testing scaffold
*
* Note that with no initialzation the sequece will repeat on every test.
*/
int main(int argc, char**argv){
while (argc > 1) {
RANDTYPE in = atoi(argv[--argc]);
printf("lambda=%d:  %d\n",in,poisson(in));
}
}
``````
-
 not very golfed, imho. – user unknown Nov 8 '11 at 4:37