我想在r中创建一个sandpile模型。它是一维的。
规则如下:
现在我写了一些代码。当然,生成初始状态很容易:
sandpile <- c(0,0,0,0,0,0,0,0,0,0)
在计算出方括号后,我设法随机丢沙并更新相邻坐标:
drop <- sample (1:10, 1)
sandpile[drop] <- sandpile[drop]+1
if(sandpile[drop] > 1) { (sandpile[drop-1] <- sandpile[drop-1]+1)
if(sandpile[drop] > 1 ) { (sandpile[drop+1] <- sandpile[drop+1]+1)
if(sandpile[drop] > 1) {sandpile[drop] <- sandpile[drop]-2
但这不会继续级联,这意味着如果沙堆[drop-1]&gt; 1,sandpile [drop-2]和sandpile [drop]不会更新。
所以...我的问题基本上是如何实现模型的其余部分,然后记录雪崩的大小(即每次更新移动的沙粒数量)以进行多次更新?
答案 0 :(得分:1)
# 10 spaces
sandpile <- c(1,1,1,1,1,1,1,0,1,1)
# Pick a random space
drop <- sample (1:10, 1)
# If the space has 0 grains of sand, add 1 grain of sand.
if(sandpile[drop]==0){
sandpile[drop] <- 1
cat("done")
# If it has 1, distribute one to each neighbor and so on
} else if(sandpile[drop]==1){
# Left neighbor(s)
i <- drop-1
while(sandpile[i] > 0 & i > 1){
if(i > 1){i <- i -1
} else if (i == 1 & sandpile[i] > 0){
break # it fell off
}else if (i == 1 & sandpile[i] == 0){
sandpile[i] <- 1
break
}
}
if(sandpile[i]==0) sandpile[i] <- 1
# Right neighbor(s)
i <- drop+1
while(sandpile[i] > 0 & i < 10){
if(i > 1){i <- i +1
} else if (i == 10 & sandpile[i] > 0){
break # it fell off
}else if (i == 10 & sandpile[i] == 0){
sandpile[i] <- 1
break
}
}
if(sandpile[i]==0) sandpile[i] <- 1
cat("done")
}