悬赏 5 个论坛币 未解决
原程序运行都正常,原程序:
b <- .2 #actual value of beta
w <- .25 #width of the uniform support set
m <- 5000 #length of the chain
burn <- 1000 #burn-in time
days <- 250
x <- numeric(m) #the chain
# generate the observed frequencies of winners
i <- sample(1:5, size=days, replace=TRUE,
prob=c(1, 1-b, 1-2*b, 2*b, b))
win <- tabulate(i)
print(win)
prob <- function(y, win) {
# computes (without the constant) the target density
if (y < 0 || y >= 0.5)
return (0)
return((1/3)^win[1] *
((1-y)/3)^win[2] * ((1-2*y)/3)^win[3] *
((2*y)/3)^win[4] * (y/3)^win[5])
}
u <- runif(m) #for accept/reject step
v <- runif(m, -w, w) #proposal distribution
x[1] <- .25
for (i in 2:m) {
y <- x[i-1] + v
if (u <= prob(y, win) / prob(x[i-1], win))
x <- y else
x <- x[i-1]
}
print(win)
print(round(win/days, 3))
print(round(c(1, 1-b, 1-2*b, 2*b, b)/3, 3))
xb <- x[(burn+1):m]
print(mean(xb))
par(mfrow=c(1,2))
plot(x, type="l")
abline(h=b, v=501, lty=3)
xb <- x[- (1:501)]
hist(xb, freq=F, xlab=bquote(beta), ylab="X", main="")
z <- seq(min(xb), max(xb), length=100)
lines(z, dnorm(z, mean(xb), sd(xb)))
改动后的程序出现了错误,我只把样本改成了4个,和prob改动了一点,改动后程序:
> b <- .2
> w <- .25
> m <- 10000
> burn <- 1000
> days <- 1604
> x <- numeric(m)
> i <- sample(1:4,size=days,replace=TRUE,prob=c(2*b,1-3*b,b,1))
> win <- tabulate(i)
> print(win)
[1] 294 327 146 837
> prob <- function(y,win) {
if (y < 0 || y >= 0.5)
return(0)
return(((2*y)/2)^win[1]*((1-3*y)/2)^win[2]*((y)/2)^win[3]*(1/2)^win[4])
}
> u <- runif(m)
> v <- runif(m,-w,w)
> x[1] <- .25
> for (i in 2:m) {
y <- x[i-1]+v
if (u <= prob(y,win)/prob(x[i-1],win))
x <- y
else
x <- x[i-1]
}
错误于if (u <= prob(y, win)/prob(x[i - 1], win)) x <- y else x <- x[i - :
需要TRUE/FALSE值的地方不可以用缺少值
原程序和改动后的程序红色字体是我对应改过的地方,可运行后就出现错误,原程序能够正常运行,请教指导!!谢谢!!