title: Estimation of pi using Monte Carlo method in fortran
body: <p>This is a a typical code to estimate pi (3.14...) value using Monte Carlo method. So I have trouble with the number of iterations of the do-while loop. Until the number of iterations less than or equal to 10000000, the approximate value of pi is correct, but when the number of iterations are more than that, the value of pi is wrong. These are the outputs for two different number of iterations.</p>
  
  <p>Output 1. (for 10000000 iterations)<br>
  Approximate value of pi is   3.14104080<br>
  Number of points in circle   7852602.00<br>
  Number of points in square   10000000.0   </p>
  
  <p>Output 2. (for 100000000 iterations)<br>
  Approximate value of pi is   4.00000000<br>
  Number of points in circle   16777216.0<br>
  Number of points in square   16777216.0 </p>
  
  <p>Fortran Code:</p>
  
  <pre><code>program estimate_pi
      implicit none
      real :: length, r, rand_x, rand_y, radius, area_square, square_points, circle_points, origin_dist, approx_pi
      integer :: i, iterations
  
      ! length of side of a square
      length = 1
      ! radius of the circle
      radius = length/2
  
      ! area of the square considered
      area_square = length * length
  
      square_points = 0
      circle_points = 0
  
      ! number of iterations
      iterations = 10000000
  
      i = 0
      do while (i &lt; iterations)
          ! generate random x and y values
          call random_number(r)
          rand_x = - length/2 + length * r
          call random_number(r)
          rand_y = - length/2 + length * r
  
          ! calculate the distance of the point from the origin
          origin_dist = rand_x * rand_x + rand_y * rand_y
  
          ! check whether the point is within the circle
          if (origin_dist &lt;= radius * radius) then
              circle_points = circle_points +  1
          end if
  
          ! total number of points generated
          square_points = square_points + 1
  
          ! approximate value of pi
          approx_pi = 4 * (circle_points/square_points)
  
          ! increase the counter by +1
          i = i + 1
      end do
  
      print*, 'Approximate value of pi is', approx_pi
      print*, 'Number of points in circle', circle_points    
      print*, 'Number of points in square', square_points
  end program estimate_pi
  </code></pre>