Created
March 14, 2014 15:24
-
-
Save cbscribe/9549921 to your computer and use it in GitHub Desktop.
Calculate Pi using the Monte Carlo method. Happy Pi Day!
This file contains hidden or 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
# Calculate Pi via the Monte Carlo method | |
# Throw darts at a square region and count how many fall into a | |
# quarter-circle. The ratio of that count to the total number of darts | |
# is 1/4 * Pi! | |
# More information (and a cool graphic) here: | |
# http://en.wikipedia.org/wiki/Monte_Carlo_method | |
# | |
# A classroom project by KidsCanCode - http://kidscancode.org/ | |
from random import random | |
import math | |
from time import time | |
# How many darts to throw? The more darts, the more accurate the estimate | |
# (but the longer it will take) | |
num_darts = 100000 | |
# Let's time how long it takes | |
start = time() | |
hits = 0 | |
for i in range(num_darts): | |
# Pick a random location in a square area | |
x, y = random(), random() | |
# See if the dart is inside the quarter-circle | |
# x^2 + y^2 = 1 is the formula for a circle | |
if x*x + y*y <= 1: | |
hits += 1 | |
# calculate Pi! | |
pi_calculated = 4 * hits / num_darts | |
# Let's also see how close we were | |
accuracy = 100 * (math.pi - pi_calculated) / math.pi | |
print("Time: %.3f sec" % (time() - start)) | |
print("Pi (estimated): %.6f (Accuracy: %.4f%%)" % (pi_calculated, accuracy)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment