Calculate Pi(π)
A long time ago, while i was browsing the internet my eye fell on a puzzle. At the beginning the puzzle seems kind of odd to me, because there was nothing more than the following sentence: “Estimate the number of Pi(π). HINT: Use Geometry” I puzzle over to find a solution, but i couldn’t. I left the puzzle unsolved for a while. A few days ago, I solved a problem using a methodology of point sampling to calculate an area. And this was the moment that my mind flipped. I knew that this was the solution that will solve the unsolved puzzle that I faced. After a few tries, the number that I receive from my terminal was close enough to the number of Pi. The code that I used to solve the puzzle is the following:
def find_pi(n):
inside = 0
for i in range(0, n):
x = random()
y = random()
if (x ** 2 + y ** 2) <= 1:
inside +=1
pi = 4 * inside / n
return pi
In order to achieve a small error the computational cost was very high. Parallel computing will save a ton of time and minimize the error of the Pi estimation. Finally, after some tries and implementations, I came with the solution that follows:
import random
import multiprocessing as Pool
import timeit
def mproc():
N = 10**7
P = 12
p = Pool(P)
print(timeit.timeit(lambda: print(sum(p.map(find_pi, [N/P]*P))/P), number=10000))
p.close()
p.join()
print("Number of Iterations: {} with {} processes".format(N, P))