# L-13 MCS 507 Wed 20 Sep 2023 : mpi4py_estimate_pi_n.py

"""
Adjustment of mpi4py_estimate_pi_2.py to work with
any number of processes to estimate Pi.
For example to use 10 processes, at the prompt, type
mpiexec -n 10 python3 mpi4py_estimate_pi_n.py
to run the script.
"""

import random
from mpi4py import MPI

COMM = MPI.COMM_WORLD
RANK = COMM.Get_rank()
SIZE = COMM.Get_size()

print(RANK, 'uses seed', RANK)
random.seed(RANK)

N = 10**7
k = 0
for i in range(0, N):
    x = random.uniform(0, 1)
    y = random.uniform(0, 1)
    if x**2 + y**2 <= 1:
        k = k + 1
R = float(k)/N

print(RANK, 'computes', R)

if(RANK > 0):
    COMM.send(R, dest=0, tag=11)
    print(RANK, 'sends', R, 'to 0')
elif(RANK == 0):
    R2 = 0
    for i in range(1, SIZE):
        S = COMM.recv(source=i, tag=11)
        print(RANK, 'received', S, 'from', i)
        R2 = R2 + S
    RESULT = 4*(R + R2)/SIZE
    print('approximation for pi =', RESULT)
