몬테카를로(Monte Carlo) 시뮬레이션 - 원 면적 구하기
Q. 몬테카를로 시뮬레이션으로 반지름이 1일 원의 면적을 구하시오
A. 수식에 의한 계산과 몬테카를로 시뮬레이션을 수행
* 수식에 의한 계산
radius <- 1
( circle_area <- pi * radius * radius )
===> 3.141593
* 몬테카를로 시뮬레이션
cal_circle_area <- function(N=1000){
x <- runif( N, -1, 1) # x value between -1 ~ 1
y <- runif( N, -1, 1) # y value between -1 ~ 1
in_area <- (x^2 + y^2) <= 1
4* mean(in_area)
}
# 시뮬레이션을 100, 1000, 10000, 100000 회 실시
count <- c( 100, 1000, 10000, 100000 )
sim_result <- sapply(count, cal_circle_area)
residuals <- circle_area - sim_result
# 실제 값과의 차이를 그래프로 표시
plot(residuals, type = "l" )
abline(0,0, lty = 3)
===> 수행 결과
sim_result : 3.40000 3.14800 3.14960 3.14716
residuals : -0.021592654 0.010407346 0.00760346 0.003207346