A Monte Carlo simulation program that calculates the area of an ellipse using random sampling. The program uses random number generation to estimate the area by counting points that fall inside an elliptical region. It iteratively improves precision by increasing the number of sample points until the result converges within a specified epsilon value. Demonstrates numerical integration techniques and statistical sampling methods.
program MonteCarlo
real :: hi, wi, xp, yp, asp, bsp, k = 1
integer :: i
hi = 2.0
wi = 2.0
xp = -1.0
yp = -1.0
asp = 1.0
bsp = 1.0
do i=1,7
k = k/10.0
print *, 'At precision of', i, ' value is', SPHArea(k)
enddo
k = 0
print *, k
contains
function checkHit(x,y)
real :: x,y
integer :: checkHit
if ((x-asp)*(x-asp)/asp/asp + (y-bsp)*(y-bsp)/bsp/bsp < 1) then
checkHit = 1
else
checkHit = 0
endif
end function checkHit
function SPHArea(eps)
real :: SPHArea, eps, Ar, prevAr
real :: x, y
real :: allp = 0, hitp = 0
integer :: cnum = 10000 , n
Ar = eps * 10
prevAr = 0
do while (abs(prevAr - Ar) > eps)
prevAr = Ar
do n = 1, cnum
call random_number(x);
call random_number(y);
x = x * wi + xp;
y = y * hi + yp;
hitp = hitp + checkHit(x,y)
! print *, allp, hitp, hitp / allp, x, y
enddo
allp = allp + cnum
Ar = hitp / allp * hi * wi
enddo
SPHArea = Ar
end function SPHArea
end program