以下代码是一个用R编写的简单马尔可夫链算法,其任务是模拟2个城镇之间租赁汽车的运动,因为客户有权在任何方便他们的城镇归还他们的汽车。这两个城镇拥有最初的租车数量,经过多次迭代,我想知道每个(城镇)的汽车最终可用性。它被提供了概率的转换矩阵(p1& p2)和完整的代码。我的问题是我无法找到代码中的缺陷,因为R没有给出任何结果。我将不胜感激任何帮助。
p1 <- c(0.6,0.4) # probabilities of Athens facilities (1st % means: stays)
p2 <- c(0.7,0.3) #probabilities of Chania facilities (1st % means: stays in town)
Athens.start <- 200 #number of cars in Athens at the start of the period
Chania.start <- 200 #number of cars in Chania at the start of the period
nsims <- 15
Athens <- rep(0,nsims+1)
Chania <- rep(0,nsims+1)
#Function for deciding whether to move or not a car from its initial facility
move <- function(p1,p2,Athens,Chania,i ) {
repeat {
#position1 is related with 1st location (Athens)
position1 <- sample(x=c(1,2),size=1,prob=p1)
if (position1==1) {
Athens[i]=Athens[i]+1
Chania[i]=Chania[i]-1
} else {
Athens[i]=Athens[i]-1
Chania[i]=Chania[i]+1
}
#position2 is related with 2nd location (Chania)
position2<-sample(x=c(1,2),size=1,prob=p2)
if (position2==1) {
Chania[i]=Chania[i]+1
Athens[i]=Athens[i]-1
} else {
Chania[i]=Chania[i]-1
Athens[i]=Athens[i]+1}
}
return(Athens[i])
return(Chania[i])
break
}
#Basic Function for simulating the movement of cars between facilities
cars.sims<-function(Athens.start,Chania.start,nsim) {
Athens<-vector(length=nsim+1)
Chania<-vector(length=nsim+1)
Athens[1]<-Athens.start
Chania[1]<-Chania.start
for (i in 1:nsim) {
Athens[i+1]<-move(p1,p2,Athens,Chania)
Chania[i+1]<-move(p1,p2,Athens,Chania)
}
Towns<-rbind(Athens,Chania)
return(Towns)
}