I'm trying to write a code in python using the Monte Carlo method to estimate pi (where pi = gamma(1/2)**2). I should write a code saying that sqrt(pi) is the area of a square enclosing the function gamma(x=1/2) times the total number of random points generated that end up inside the function, divided by the total number of points generated.
Just to show what kind of code I'm talking about, here I did it without using the Gamma function (still is Monte Carlo method). Here Pi is evaluated as being the area of a 2x2 square times the number of points ending up in the circle of unit 1 divided by the total number of points generated. The criterion for a point to be in the unit circle is Pythagorean (np.sqrt(xx+yy)<=1).
inside =0
n=100000
for i in range(0,n):
x=np.random.rand()
y=np.random.rand()
if np.sqrt(x*x+y*y)<=1:
inside = inside+1
pi = 4.0*inside/n
print pi
I'm not sure how you would determine the area enclosing Gamma(1/2) and what the criterion for a point to end up inside the function would be here.
Anyone have an idea?
Thanks!
Judging from you question I feel like your are taking PHY324. ;) I am confused about the same thing. I have a code set up and I am no python expert but maybe this might help.
import random
from math import *
number_of_points = 10000
points_in = []
points_outside = []
for i in range(number_of_points):
rand_number1 = random.random()
rand_number2 = random.random()
if rand_number2 < (exp(-1*rand_number1))*(rand_number1**(-0.5)):
points_in.append(1)
else:
points_outside.append(1)