「半個數學系 + 一個計算機科學系 = Deep Learning初級班」spa
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,參考線