Hello, i have this excersice in R studio Write a function in R that generates simulations...

Free

50.1K

Verified Solution

Question

Statistics

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ónrpoisI <- 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)

Answer & Explanation Solved by verified expert
4.1 Ratings (696 Votes)

# 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         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))


Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students