# without fixing the seed
simllh <- function(sd, y, Ns){
simdist <- density(rnorm(Ns, mean = 0, sd = sd))
llh <- sapply(y, function(x){ simdist$y[which.min((x - simdist$x)^2)] })
return(-sum(log(llh)))
}
# same function with fixed seed
simllh.fix.seed <- function(sd,y,Ns){
set.seed(48)
simdist <- density(rnorm(Ns,mean=0,sd=sd))
llh <- sapply(y,function(x){simdist$y[which.min((x-simdist$x)^2)]})
return(-sum(log(llh)))
}
我们可以通过一个简短的蒙特卡罗研究来检查两个函数在发现真参数值时的相对性能:
N <- 20; sd <- 2 # features of simulated data
est1 <- rep(NA,1000); est2 <- rep(NA,1000) # initialize the estimate stores
for (i in 1:1000) {
as.numeric(Sys.time())-> t; set.seed((t - floor(t)) * 1e8 -> seed) # set the seed to random seed
y <- rnorm(N, sd = sd) # generate the data
est1[i] <- optim(1, simllh, y = y, Ns = 1000, lower = 0.01)$par
est2[i] <- optim(1, simllh.fix.seed, y = y, Ns = 1000, lower = 0.01)$par
}
hist(est1)
hist(est2)