Created
October 10, 2019 08:22
-
-
Save erijpkema/0fe45562b3880af337fe5bf6ef5d1377 to your computer and use it in GitHub Desktop.
monte carlo method of estimating pi using mpi
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
#!/usr/bin/env python3 | |
''' listing 6: pi_mp.py | |
Multiprocessing based code to estimate the value of PI | |
using monte carlo sampling | |
Ref: http://math.fullerton.edu/mathews/n2003/montecarlopimod.html | |
Adapted for python3 and mpi from: | |
https://gist.githubusercontent.com/amitsaha/2036026/raw/77e45e5a9f6c8e030a9fc7a8f5b6450bc8348a28/pi_mp.py | |
''' | |
from mpi4py import MPI | |
import random | |
def monte_carlo_pi_part(n): | |
""" | |
caculate the number of points in the unit circle | |
out of n points. | |
""" | |
count = 0 | |
for i in range(n): | |
x = random.random() | |
y = random.random() | |
# if it is within the unit circle | |
if x * x + y * y <= 1: | |
count = count + 1 | |
return count | |
if __name__ == '__main__': | |
comm = MPI.COMM_WORLD | |
rank = comm.Get_rank() | |
number_nodes=comm.Get_attr(MPI.UNIVERSE_SIZE) | |
# Nummber of points to use for the Pi estimation | |
n = 10000000 // number_nodes | |
# iterable with a list of points to generate in each worker | |
# each worker process gets n/np number of points to calculate Pi from | |
# Do the calculation and send it to the first worker. | |
comm.send(monte_carlo_pi_part(n), dest=0, tag=42) | |
# Receive all the samples. | |
count = 0 | |
if rank == 0: | |
print(f'Number nodes: {number_nodes}') | |
for node in range(number_nodes): | |
print(f'node: {node}') | |
count += comm.recv(source=node, tag=42) | |
print("Esitmated value of Pi: ", count / (n * number_nodes) * 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment