Created
February 3, 2012 13:10
-
-
Save hinnerk/1730113 to your computer and use it in GitHub Desktop.
π — calculated by chance
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 | |
import multiprocessing | |
from datetime import datetime | |
def run_simulation(throws=1000000): | |
hits = 0 | |
count = 0 | |
while count < throws: | |
count += 1 | |
x = random() | |
y = random() | |
distance = (x ** 2 + y ** 2) ** 0.5 | |
hits += distance <= 1 | |
return hits | |
if __name__ == '__main__': | |
start = datetime.now() | |
print "Starting simulation..." | |
pool = multiprocessing.Pool() | |
throws = 1000000000 # 1.000.000.000 throws | |
tasks = [throws / multiprocessing.cpu_count()] * multiprocessing.cpu_count() | |
r = pool.map_async(run_simulation, tasks) | |
hits = sum(r.get()) | |
print "Pi, calculated by chance: ", 4 * (hits / float(throws)) | |
print "Time: ", datetime.now() - start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment