# newbie - poisson numbers

• 10-27-2008
fireflym
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. :(
• 10-27-2008
robwhit
Aha master5001... so much for your latex poll. :D
• 10-28-2008
tabstop
Maybe ((double)rand()) -- make sure the rand gets casted before the division, otherwise u is always 0.