Skip to content

Instantly share code, notes, and snippets.

@armonge
Created September 11, 2014 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save armonge/03511c9be54c6375d9c0 to your computer and use it in GitHub Desktop.
Save armonge/03511c9be54c6375d9c0 to your computer and use it in GitHub Desktop.
Calculating PI with Python
import functools
import random
import math
from concurrent import futures
def map_d(c):
return math.hypot(random.random(), random.random())
def reduce_d(count_inside, d):
if d < 1:
return count_inside + 1
return count_inside
def generate_random(count):
d_list = map(map_d, range(0, count))
count_inside = functools.reduce(reduce_d, d_list)
return count_inside
def main():
count = 100000000
cores = 4
count_inside = 0
with futures.ProcessPoolExecutor(cores) as executor:
for val in executor.map(generate_random, (int(count/cores) for _ in range(cores)) ):
count_inside += val
print(4.0 * count_inside / count)
if __name__ == '__main__':
main()
import functools
import random
import math
import multiprocessing
def map_d(c):
return math.hypot(random.random(), random.random())
def reduce_d(count_inside, d):
if d < 1:
return count_inside + 1
return count_inside
def generate_random(q, count):
d_list = map(map_d, range(0, count))
count_inside = functools.reduce(reduce_d, d_list)
q.put(count_inside)
def main():
count = 100000000
cores = 4
q = multiprocessing.Queue(maxsize=cores)
for i in range(cores):
p = multiprocessing.Process(target=generate_random, args=(q, int(count/cores)))
p.start()
count_inside = 0
for _ in range(cores):
count_inside += q.get()
print(4.0 * count_inside / count)
if __name__ == '__main__':
main()
import functools
import random
import math
def map_d(c):
return math.hypot(random.random(), random.random())
def reduce_d(count_inside, d):
if d < 1:
return count_inside + 1
return count_inside
def main():
count = 100000000
d_list = map(map_d, range(0, count))
count_inside = functools.reduce(reduce_d, d_list)
print(4.0 * count_inside / count)
if __name__ == '__main__':
main()
import queue
import functools
import random
import math
import threading
def map_d(c):
return math.hypot(random.random(), random.random())
def reduce_d(count_inside, d):
if d < 1:
return count_inside + 1
return count_inside
def generate_random(q, count):
d_list = map(map_d, range(0, count))
count_inside = functools.reduce(reduce_d, d_list)
q.put(count_inside)
def main():
count = 100000000
threads = 4
q = queue.Queue(maxsize=threads)
for i in range(threads):
t = threading.Thread(target=generate_random, args=(q, int(count/threads)))
t.daemon = True
t.start()
count_inside = 0
for _ in range(threads):
count_inside += q.get()
print(4.0 * count_inside / count)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment