from mpi4py import MPI

import random
import socket


comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
host = socket.gethostname()

if rank == 0:
    print(f"[INFO] World size = {size}")

comm.Barrier()
print(f"Rank {rank:02d} on host {host}")

total_samples = 2_000_000
local_samples = total_samples // size
random.seed(1234 + rank)

hits = 0
for _ in range(local_samples):
    x = random.random()
    y = random.random()
    if x * x + y * y <= 1.0:
        hits += 1

total_hits = comm.reduce(hits, op=MPI.SUM, root=0)

if rank == 0:
    samples_used = local_samples * size
    pi_estimate = 4.0 * total_hits / samples_used
    print(f"[RESULT] pi ~= {pi_estimate:.6f} using {samples_used} samples")
