Numerical methods

Monte Carlo method for beginners

keywords: Monte Carlo method, random number, random points, estimate of  π, SageMath.

This example is one of the exercises included in the Diploma thesis: Ohman, L. (2017). Parallel programming. Košice: TUKE LF.  

The program uses the random points and the unit quarter circle to estimate the value of number π. We can set up the number of random points by using a slider, interactively. The Diploma thesis as mentioned above also contains a parallel version of this Monte Carlo Method.

@interact
def NPoints(n = slider(vmin=1000, vmax=20000, step_size=1000, default=10000)):

  var("x")
  f(x) = sqrt(1-x^2)                   
#  function of unit quarter circle
  circle = plot(f(x),x,0,1)            
#  unit quarter circle
  l1=line([(0,1),(1,1)])                #  define an unit square
  l2=line([(1,0),(1,1)])
  ptsin = 0

  import random                        
# load the library of random functions
  list_pts = [(random.uniform(0, 1),    # generate random points from [0,1] and insert to list_pts
             random.uniform(0, 1))
                 for i in range(n)]     # n times (n = number of all random points)

  list_ptsin = []                 # list of points inside the circle
  list_ptsout = []                # list of points outside the circle

  for point in list_pts:                #   test/computation for inside/outside points               
    if (point[0]^2+point[1]^2<1):
        list_ptsin.append(point)
        ptsin +=1
    else:
        list_ptsout.append(point)
       
  inpoints= list_plot(list_ptsin ,color='red', size = 10)    # define inside points / red color 
  outpoints= list_plot(list_ptsout,color='blue', size=10)    # define outside points / blue color
       
  pi = 4*(ptsin*1.0 / len(list_pts))
  estimate  = " = "
  estimate += str(pi.n())
  # show(estimate)

  show(LatexExpr("\\pi\\simeq 4*(inpoints)/n")+estimate)       

  (circle+l1+l2+inpoints+outpoints).show()        #
Show quarter circle, axes, unit square, points

Click the "Activate" button below to apply for the above-listed program.

You need to enable Javascript in your browser for interactive pages.

23.12.2019, P.Szabó