Skip to content

Instantly share code, notes, and snippets.

@sashabaranov
Created September 23, 2012 07:40
Show Gist options
  • Save sashabaranov/3769228 to your computer and use it in GitHub Desktop.
Save sashabaranov/3769228 to your computer and use it in GitHub Desktop.
Pythonic parallel π calculation
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