[英]R Poisson simulation function
我想写一个 function 来计算在 n 次不同试验中到达时间 t 的次数。 我知道arguments应该包括指数参数lambda、时间t和要采样的计数n。 它应该返回一个包含 n 个元素的向量,对应于计数。
进展:我创建了一个 function 来计算直到时间 t 的事件数,我需要使用 rexp() function。
但是我该怎么做这个泊松 function?
下面模拟一个泊松过程。 function Nt
需要两个arguments,指数速率和时间限制。
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.