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

时间:2023-03-08 22:26:05

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

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

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,参考线