Created
September 23, 2012 07:40
-
-
Save sashabaranov/3769228 to your computer and use it in GitHub Desktop.
Pythonic parallel π calculation
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
import sys | |
from multiprocessing import Pool | |
from random import random | |
def calculate_pi(iters): | |
""" Worker function """ | |
points = 0 # points inside circle | |
for i in iters: | |
x = random() | |
y = random() | |
if x ** 2 + y ** 2 <= 1: | |
points += 1 | |
return points | |
if __name__ == "__main__": | |
if len(sys.argv) != 3: | |
print "Usage: python pi.py workers_number iterations_per_worker" | |
exit() | |
procs = int(sys.argv[1]) | |
iters = float(sys.argv[2]) # 1E+8 is cool | |
p = Pool(processes=procs) | |
total = iters * procs | |
total_in = 0 | |
for points in p.map(calculate_pi, [xrange(int(iters))] * procs): | |
total_in += points | |
print "Total: ", total, "In: ", total_in | |
print "Pi: ", 4.0 * total_in / total | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment