将正态曲线转换为R中的蒙特卡罗函数

时间:2015-04-27 20:51:38

标签: r curve normal-distribution montecarlo

我有一个蒙特卡罗问题需要与Normal曲线进行比较,现在我有了这个:

monte_carlo <- function(T){

  K <- 2
  beta1 <- 0.131                   
  beta2 <- 0.406
  betaa <- c(beta1,beta2)
  beta<-as.vector(betaa)
  phi <- 0.6
  c <- 2
  ni<- as.vector(rnorm(T))
  x0 <- rnorm(1,(c/(1-phi)),(1/(1-(phi)^2)^(0.5)))

  # Gerar x
  x_3 <- rep(0,T)
  x_3[1]<- c+phi*x0+ni[1]
  for(i in 2:T){
    x_3[i]<-c+phi*x_3[i-1]+ni[i]
  }

  # Fazer o loop
  N <- 100000
  vEst <- matrix(,100000,K)
  vT <- vEst


  for(j in 1:N){
    # Gerando e
    e <- as.vector(rnorm(T))        

    # Gerando y
    y<- rep(0,T)
    for(i in 1:T){
      y[i]<- beta1+beta2*x_3[i]+e[i]
    }

    X <- matrix(1,T,K)
    X[,2]<- x_3
    # Estimando b por MQO
    b.est<- function(y,X){
      xy <- t(X)%*%y                  # X'Y 
      xxi <- solve(t(X)%*%X)          #(X'X)^(-1)
      b <- as.vector(xxi%*%xy)
      return(b)
    }


    # Chamando os resultados

    vEst[j,] <- b.est(y,X)

  }

  # Obtendo as médias
  b_mean <- colMeans(vEst)


  # Plotando os gráficos 
  G_b1<- plot(density(vEst[,1])) 
  G_b2<-plot(density(vEst[,2]))


  table <- cbind(Medias_dos_estimadores=b_mean, Grafico_b1=G_b1, Grafico_b2=G_b2)

  return(list(b=table))
}

有了这个,我得到了,例如,这个:

> monte_carlo(23)
$b
     Medias_dos_estimadores Media_das_estatisticas_t
[1,]              0.1230776             -0.008260573
[2,]              0.4076724              0.001772357

enter image description here enter image description here

但是,我还需要绘制一条正常曲线进行比较。我该如何绘制它?

ps:在这种情况下,sd由下式给出:

var.est<- function(y,x){
  x <- as.matrix(cbind(int=1,x))
  y <- as.vector(y)

  T <- length(y)
  K <- ncol(x)-1

  xy <- t(x)%*%y                  # X'Y 
  xxi <- solve(t(x)%*%x)          #(X'X)^(-1)
  b <- as.vector(xxi%*%xy)        #estimated coefficients

  yhat <- as.vector(x%*%b)        #predicted values for y
  res <- y-yhat                   #model residual

  sse <- t(res)%*%res             # or sum(res^2) which is also t(res)%*%res
  sigma2 <- sse/(T-K)
  s2 <- sigma2[1,1]

  est.var <- s2*solve(crossprod(x)) #coefficient standard errors
  var.est <- rep(0,K)
  for(i in c(1:K)){
    var.est[i] <- est.var[i,i]
  }
  return(var.est)
}

0 个答案:

没有答案