Created
September 9, 2017 21:12
-
-
Save samueleverett01/345377de00b5861786e3b55f0982220f to your computer and use it in GitHub Desktop.
Find the value of pi using Monte Carlo sampling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import random | |
from math import pow, sqrt | |
#set the number of trials that will be run to calculate pi | |
trial=10000000 | |
hits=0.0 | |
throws=0.0 | |
# Monte Carlo step | |
# Create a circle, split into 4 quadrents, with radius = 1 | |
# Calculate ratio of points that fall inside circle quadrent and outside circle quadrent to get pi | |
for i in range(1,trial): | |
x=random() | |
y=random() | |
location=sqrt(pow(x, 2)+pow(y,2)) | |
if location<=1: | |
hits+=1 | |
throws+=1 | |
else: | |
throws+=1 | |
ratio=hits/throws | |
pi=ratio*4 | |
print (pi) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment