[Bayes] Point --> Hist: Estimate "π" by R

Verify the Monte Carlo sampling variability of "π".

 

 

p = π/4 与 所得 0.7854 比较接近,故满足 Central Limit theorem。

simulation = function(sampleSize){
  c = rep(0,sampleSize)
  countIn = 0
  for(i in 1:sampleSize){
    x = runif(1,-1,1)
    y = runif(1,-1,1)
    if(sqrt(x*x + y*y) <= 1){
      countIn = countIn + 1
    }
    piHat = countIn / i
    c[i] = piHat
  }
  return(c)
}

pointEstimate = function(testCount){
  cc = rep(0,testCount)
  for(i in 1:testCount){
    sampleSize = 1000
    res = simulation(sampleSize)
    cc[i] = res[1000] 
  }
  return(cc)
}

testCount = 1000
res = pointEstimate(testCount)
/* 获得很多要构成长条的点 */
hist(res, freq
= F, breaks = testCount) mean(res)

 

posted @ 2017-03-29 13:13  郝壹贰叁  阅读(185)  评论(0编辑  收藏  举报