Skip to main content

Determine value of pi by Monte Carlo method

We will approximate value of π\pi by Monte Carlo method. We will generate random number in a square of radius 2 unit; x = (-1, 1) and y = (-1, 1). We will count how many points are inside the circle of radius 1 unit. Area of the square = 4 square unit, while the are of circle is π\pi (unit radius circle). Use this ratio to approximate the value of π\pi.

src/20_monte_carlo_pi.f90
PROGRAM pi
IMPLICIT NONE

INTEGER, PARAMETER :: iteration = 1000000
REAL :: x, y
REAL :: x_lo = -1.0
REAL :: x_hi = 1.0
REAL :: y_lo = -1.0
REAL :: y_hi = 1.0
INTEGER :: i, monte_area = 0

DO i = 1, iteration
CALL random_number(x)
CALL random_number(y)

x = x_lo + x * (x_hi - x_lo);
y = y_lo + y * (y_hi - y_lo);

IF (x * x + y * y < 1) THEN
monte_area = monte_area + 1;
END IF
END DO

PRINT *, "pi = ", 4.0 * monte_area / iteration

PRINT *, "relative error = ", abs(1.0 * monte_area / iteration &
- ATAN(1.0D0)) / ATAN(1.0D0)

END PROGRAM pi