# Thread: newbie - poisson numbers

1. ## newbie - poisson numbers

Hi everyone,

Ive been trying to create a function to generate random poisson numbers. Here is the Knuth algorithm from wikipedia

algorithm poisson random number (Knuth):
init:
Let L ← e−λ, k ← 0 and p ← 1.
do:
k ← k + 1.
Generate uniform random number u in [0,1] and let p ← p &#215; u.
while p ≥ L.
return k − 1.

I coded this like this:

Code:
``` unsigned long PoissonRandomNumber(double landa){

double l=exp(-landa);
unsigned long k=0;
double p=1;
while (p>=l)
{
k=k+1;
double u= (double)rand() / RAND_MAX;
p=p*u;
}
return k-1;```

But i only get 0s from using this. Any help would be greatly greatly appreciated! Actually, any help on any code to generate poisson random numbers would be huge help to me.

EDIT: I also tried it like this code I found on the web:

Code:
```double p=exp(-landa);
double g=p;
double u= (double)rand() / RAND_MAX;

unsigned long k=0;
while (u>g)
{
p*=(landa/(double)(++k));
g+=p;
};
return k;
}```
This just gives me the same number everytime when i put in a particular landa.  2. Aha master5001... so much for your latex poll.  3. Maybe ((double)rand()) -- make sure the rand gets casted before the division, otherwise u is always 0. Popular pages Recent additions 