Monte Carlo Process: 饾湅 approximation

1 minute read

Updated:

The task is to compute an approximation to 饾湅 using Monte Carlo.

Python is used for representation.


Version 1: Draw unit circle to the coordinate and plot the dots.

import numpy as np
import matplotlib.pyplot as plt

let鈥檚 setup the initial variables.

trial = 1000
inCircle = 0

And draw the unit circle to the plt.

circle = plt.Circle((0, 0), radius = 1, color='black', fill=False)
ax = plt.gca()
ax.add_artist(circle)

And then, plot the random coordinate.

for i in range(trial):
	x = np.random.uniform(-1,1)
	y = np.random.uniform(-1,1)
    if (x**2 + y**2 < 1):
        inCircle += 1
        plt.scatter(x, y, s = 1, color = "black")
    else:
        plt.scatter(x, y, s = 1, color = "blue")   

Show the canvas and calculate the answer.

plt.axis([-1, 1, -1, 1])
plt.show()
ratio = inCircle/trial
 = ratio * 4 # result is here

The result comes out as:

img1


Version 2: We want to see the converging process.

Basic setup is as follows:

import numpy as np
import matplotlib.pyplot as plt
import math

Firstly, lets define function that does montecarlo processes to estimate pi.

def monteCarloPi(trial):
	cnt = 0
    for i in range(trial):
	x = np.random.uniform(-1,1)
	y = np.random.uniform(-1,1)
    
	if (x**2 + y**2 < 1):
		cnt = cnt+1

	return (cnt/trial)*4

And let鈥檚 define another function to plot the result. if the value is within 系, let鈥檚 plot the point in blue color. else, let鈥檚 do it in red.

def plotApproxProcess(x, , trial):
	plt.hlines(, 1, trial, colors='black', linestyles='solid', label='蟺')
	for i in range(1, trial+1):
		result = monteCarloPi(i)
		if abs(result - x) < :
			plt.scatter(i, result, s = 1, color = "blue")
		else:
			plt.scatter(i, result, s = 1, color = "red")

And show the result.

 = math.pi
 = 0.1
plotApproxProcess(, , 1000)
plt.show()

The result comes out as:

img2


Code in jupyter notebook is available at my github.

Leave a comment