Skip to content

Instantly share code, notes, and snippets.

@ike-okonkwo
Last active May 29, 2021 17:45
pi estimate via Monte Carlo simulation
#!/usr/bin/env python
# Estimating the value of pi via Monte Carlo simulation
from random import random
import numpy as np
import matplotlib.pyplot as plt
trials = list(np.linspace(10,1000000, 1000)) # different number of trials
pi = []
def mc_multiple_runs(trials, hits = 0):
'''
(float, int) -> (float)
This function returns the number of hits you get for each monte carlo run
'''
for i in range(int(trials)):
x, y = random() , random() # generate random x,y in (0,1] at each run
if x**2 + y**2 < 1 : # defines the edge of the quadrant
hits = hits + 1
return float(hits)
for i in trials:
pi.append(4*(mc_multiple_runs(i)/i))
print 'hits : %d, trials: %d, estimate pi = %1.4F' %(mc_multiple_runs(i), i, 4*(mc_multiple_runs(i)/i) )
# plot graphs
plt.plot(trials, pi, 'g')
plt.title('Estimating the value of pi via Monte Carlo')
plt.xlabel('# of Trials')
plt.ylabel('Estimated value of pi')
plt.ylim(3.11,3.17)
plt.show()
plt.hist(pi, bins = np.linspace(3.12,3.16,50), color='green')
plt.title('Estimating the value of pi via Monte Carlo')
plt.xlabel('Estimated value of pi')
plt.ylabel('Trials')
plt.xlim(3.13,3.15)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment