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

"""
Applies a simple Monte Carlo method to estimate Pi.
At the command prompt, type
mpiexec -n 2 python3 mpi4py_estimate_pi_2.py
to run the script.
"""

import random
from mpi4py import MPI

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

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 == 1):
    COMM.send(R, dest=0, tag=11)
    print(RANK, 'sends', R, 'to 0')
elif(RANK == 0):
    S = COMM.recv(source=1, tag=11)
    print(RANK, 'received', S, 'from 1')
    RESULT = 2*(R + S)
    print('approximation for pi =', RESULT)
