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

“半个数学系 + 一个计算机科学系 = Deep Learning初级班”

 

 

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) * 4
    c[i] = piHat
  }
  return(c)
}

sampleSize = 1000
res = simulation(sampleSize)

/* res: 存储着所有的点 */
plot(res[
1:sampleSize], type = 'l')  // 画点连成的线 lines(rep(pi, sampleSize)[1:sampleSize], col = 'red') // 画PI,参考线

 

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