MC-INTEGRATION
! Program name: MC-INTEGRATION
! INTEGRATION BY MONTE CARLO METHOD
! INTEGRAL BY MEAN FUNCTION
! EXAMPLE FUNCTION f= 1/(1+x**2)
! In the interval (0,1) the integral is 0.78540
Program monte_carlo
real :: f, f2,
integrand, integral, sigma, a, b, x
integer :: i, n
data exact/.78540/
Print *, "Enter the grid of the
integration, n: "
Read *, n
If (n .eq. 0) stop
Print *, "Enter the lower limit and upper
limit of integration, a, b:"
Read *, a, b
! For the integral in the example, a=0 and b=1
f= 0.0
f2=0.0
call random_seed()
do i=1,n
call
random_number(x)
x=x*b
f=
f+integrand(x)
f2=f2+(integrand(x)**2)
! print
*, x, f, f2 !OPTIONAL VISUALIZATION
End do
f=f/n
f2=f2/n
integral=(b-a)*f
sigma=(b-a)*sqrt((f2-f**2)/n)
Print *,
Print *, integral, sigma, "error= ",
exact-integral
End program monte_carlo
function integrand(x) result(func)
Implicit none
Real
:: func, x
func=
1./(1.+x**2)
Comentários
Postar um comentário