Created
February 13, 2015 00:40
-
-
Save lykkin/4c78353359af480c176c to your computer and use it in GitHub Desktop.
measuring accuracy as a function on number of samples for the monte carlo approx of pi
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 pi, fabs | |
accuracies = { | |
'10': 0, | |
'100': 0, | |
'1000': 0, | |
'10000': 0, | |
'100000': 0, | |
'1000000': 0, | |
'10000000': 0, | |
} | |
num = 0 | |
num_samples = [10, 100, 1000, 10000, 100000, 1000000, 10000000] | |
average_val = 0 | |
for samples in num_samples: | |
for n in range(1, 101): | |
for _ in range(samples): | |
x, y = random(), random() | |
if x*x + y*y <= 1: | |
num += 1 | |
average_val *= (n-1) | |
average_val += 4*(float(num)/samples) | |
average_val /= n | |
num = 0 | |
print 'With ' + str(samples) + ' samples we have an error margin of ' + str(fabs(average_val - pi)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment