Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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);
share|improve this question
Why is this question restricted to C? Might be a better fit for SE. – user unknown Nov 8 '11 at 4:37

1 Answer

up vote 1 down vote accepted

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));
  }
}
share|improve this answer
not very golfed, imho. – user unknown Nov 8 '11 at 4:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.