gpt4 book ai didi

r - 向量化模拟

转载 作者:行者123 更新时间:2023-12-02 22:41:00 24 4
gpt4 key购买 nike

为了全神贯注于矢量化,试图让一些模拟更快,我发现了这个非常基本的流行病模拟。代码来自书http://www.amazon.com/Introduction-Scientific-Programming-Simulation-Using/dp/1420068725/ref=sr_1_1?ie=UTF8&qid=1338069156&sr=8-1

#program spuRs/resources/scripts/SIRsim.r

SIRsim <- function(a, b, N, T) {
# Simulate an SIR epidemic
# a is infection rate, b is removal rate
# N initial susceptibles, 1 initial infected, simulation length T
# returns a matrix size (T+1)*3 with columns S, I, R respectively
S <- rep(0, T+1)
I <- rep(0, T+1)
R <- rep(0, T+1)
S[1] <- N
I[1] <- 1
R[1] <- 0
for (i in 1:T) {
S[i+1] <- rbinom(1, S[i], (1 - a)^I[i])
R[i+1] <- R[i] + rbinom(1, I[i], b)
I[i+1] <- N + 1 - R[i+1] - S[i+1]
}
return(matrix(c(S, I, R), ncol = 3))
}

模拟的核心是for 循环。我的问题是,因为代码从 S[i] 生成了 S[i+1]R[i+1] 值和 R[i] 值,是否可以使用应用函数对其进行矢量化?

非常感谢

最佳答案

很难对迭代计算进行“矢量化”,但这是一个模拟,模拟可能会运行多次。因此,通过添加参数 M(要执行的模拟次数),分配一个 M x (T + 1) 矩阵,然后填充连续的列,从而同时进行所有模拟每次模拟的(次)。这些更改似乎非常简单(所以我可能犯了一个错误;我特别关心在 rbinom 的第二个和第三个参数中使用向量,尽管这与文档)。

SIRsim <- function(a, b, N, T, M) {
## Simulate an SIR epidemic
## a is infection rate, b is removal rate
## N initial susceptibles, 1 initial infected, simulation length T
## M is the number of simulations to run
## returns a list of S, I, R matricies, each M simulation
## across T + 1 time points
S <- I <- R <- matrix(0, M, T + 1)
S[,1] <- N
I[,1] <- 1
for (i in seq_along(T)) {
S[,i+1] <- rbinom(M, S[,i], (1 - a)^I[,i])
R[,i+1] <- R[,i] + rbinom(M, I[,i], b)
I[,i+1] <- N + 1 - R[,i+1] - S[,i+1]
}
list(S=S, I=I, R=R)
}

关于r - 向量化模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10770107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com