我一直在尝试在 R 中的 n 循环算法上实现随机游走。
通过 n 循环,我的意思是整数 Zn 的集合,或模 n。基本上,它是 Levin、Peres 和 Wilmer 所著的“马尔可夫链和混合时间”一书中的示例 5.3.1。目的如下:考虑两条链,模拟两个粒子 X 和 Y 在 Zn 上的运动,起点为 X1 和 Y1。通过掷硬币,我们决定哪个粒子将移动(除非它们已经耦合,否则粒子不能同时移动);方向由另一枚公平硬币决定。一旦两个粒子发生碰撞,它们就会一起移动。它是实现 CFTP 算法的研究项目的一部分,因此链的长度应该具有预定义的值,例如 T。
代码不运行并出现错误消息。错误是“找不到对象'res'”。但是,我之前将“res”定义为一个列表来存储函数的输出。为什么会发生这种情况,如何解决?
我有两个脚本:在第一个中,代码被分成较小的辅助函数;第二个可能更混乱,因为我试图将所有辅助函数放在一个函数中。任何帮助都感激不尽。
这是脚本 2。
# X1 - initial state of chain X
# Y1 - initial state of chain Y
# T - "length" of a chain, number of steps the chains will run for.
# n - length of the n-cycle, i.e., Zn.
Main_Function <- function (X1 = 8, Y1 = 4 , T = 20, n = 6){
X <- rep( X1, T) %% n # X, Y and res will store the results
Y <- rep( Y1, T) %% n
res <- list(X,Y) # Here I defined the object res. Later on R encounters an error "object 'res' not found".
ps <- TakeOneStep() # TakeOneStep is a function defined below
return(ps)
}
TakeOneStep <- function(){
incr_same <- sample(c(-1, 0, 1), size = 1, prob = c(1/4, 1/2, 1/4)) #direction of the particles after they have coupled
incr_dif <- sample(c(-1,1), size = 1, prob = c(1/2, 1/2)) # direction of the particles before coupling occurred.
choice <- runif(T) # determines which chain moves, before coupling occurred.
for(t in 2:T){
if(res[[1]][t-1]%%n == res[[2]][t-1]%%n){
res[[1]][t] <- (res[[1]][t-1] + incr_same) %% n
res[[2]][t] <- (res[[2]][t-1] + incr_same) %% n
}else{ if(choice[t] < 0.5) {
res[[1]][t] <- (res[[1]][t-1] + incr_dif) %% n
}else{res[[2]][t] <- (res[[2]][t-1] + incr_dif)%%n}
}
}
return(res)
}