[R] Viewing function source

Thomas Lumley tlumley at u.washington.edu
Tue Aug 26 22:26:15 CEST 2003


On Tue, 26 Aug 2003, Paul Meagher wrote:

>
> Personally, I would like to see a counting process implementation of an
> poisson random number generator.  I suspect it would be much slower than
> rpois.c (because it would likely depend upon setting a num_frames iteration
> counter) and less accurate, but would be much more compact and give more
> intuitive insight and understanding of a numerical process that generates
> the poisson random deviates.  I am not very fluent yet in R programming to
> attempt this.  I could take a stab at it with PHP which I am much more
> fluent in if I am not barking up the wrong tree on this conjecture.
>

You can generate Poisson random numbers from a Poisson process like this:

rfishy<-function(lambda){
    t <- 0
    i <- -1
    while(t<=lambda){
        t<-t-log(runif(1))
        i<-i+1
    }
    return(i)
}

The name of this generator is descriptive, not a pub. It is very slow for
large lambda, and incorrect for extremely large lambda (and possibly for
extremely small lambda). If you only wanted a fairly small number of
random variates with, say, 1e-6<lambda<100, then it's not too bad.

But why would anyone *want* to code their own Poisson random number
generator, except perhaps as an interesting student exercise?


	-thomas




More information about the R-help mailing list