问题描述
我想写一个函数来计算 n 中到时间 t 的到达次数 不同的试验。我知道参数应该包括指数参数 lambda、时间 t 和要采样的计数 n。它应该返回一个包含 n 个元素的向量,对应于计数。
进度:我创建了一个函数来计算时间 t 之前的事件数,我将需要使用 rexp() 函数。
但是我如何做这个泊松函数?
解决方法
以下模拟泊松过程。函数 Nt
有两个参数,指数速率和时间限制。
Nt <- function(lambda = 1,t){
S <- 0 # Total time,sum of X's
n <- 0L # Number of events
repeat{
X <- rexp(1,lambda) # New time between events
if(S + X > t) break # Above the limit time t?
S <- S + X # No,update total time S
n <- n + 1L # and the nr. of events counter
}
n
}
set.seed(2021)
Rate <- 2
Time <- 10
N <- replicate(1e4,Nt(lambda = Rate,t = Time))
tbl <- table(N)
plot(tbl/sum(tbl),lwd = 10,col = "grey")
lines(0:40,dpois(0:40,lambda = Time*Rate),type = "h",col = "red")