In: Statistics and Probability
Hello, i have this excersice in R studio
Write a function in R that generates simulations of a Poisson random variable as follows: define I = [λ], and use p_i + 1 = λp_i / (i + 1) to determine F recursively. Generate a random number U, determine if X≤I by comparing if U≤F (I). If X≤I searches downwards starting at I, otherwise it searches upwards starting from I + 1. Compare the time it takes for the two algorithms in 5000 simulations of a Poisson random variable with parameter λ = 10,200,500.
example
# Poisson usando Inversión rpoisI <- function(lambda = 1){ U <- runif(1) i <- 0 p <- exp(-lambda) P <- p while(U >= P){ p <- lambda * p / (i + 1) P <- P + p i <- i + 1 } i } sims_pois <- rerun(2000, rpoisI()) %>% flatten_dbl() ggplot() + geom_histogram(aes(x = sims_pois, y = ..density..), binwidth = 1)
# Poisson Random generator
### Compare the time it takes for the two algorithms in 5000
simulations of
# a Poisson random variable with parameter λ =
10,200,500.
poisn.gen=function(lambda,size){
x=NULL
for (j in 1:size) {
u=runif(1)
p=exp(-lambda)
f=p
i=0
s=0
while(s==0){
if(u<f){
x=append(x,i,after =
length(x))
s=1
}
else{
p=(p*lambda)/(i+1)
f=f+p
i=i+1
}
}
}
return(x)
}
poisn.gen(10,5000)
poisn.gen(200,5000)
poisn.gen(500,5000)
hist(poisn.gen(500,5000))