keywords: Monte Carlo method, random number,
random points, estimate of π, SageMath.
This example is one of
the exercises included in theDiploma
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.
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