zl程序教程

您现在的位置是:首页 >  其它

当前栏目

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

gt quot by point hist --& Bayes
2023-09-27 14:23:25 时间

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)