import numpy as np
from mpi4py import MPI
import time

comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
print ("I am rank {0} from {1}". format(rank, size))
if rank is 0:
    N = np.array(10000, 'i')
else: 
    N = np.array(0, dtype='i')

comm.Bcast([N, MPI.INT], root=0)
start = time.time()
h = 1.0 / N; s = 0.0
for i in range(rank, N, size):
    x = h * (i + 0.5)
    s += 4.0 / (1.0 + x**2)
PI = np.array(s * h, dtype='d')
PI_ALL= np.array(0, dtype='d')
comm.Reduce([PI, MPI.DOUBLE], [PI_ALL, MPI.DOUBLE],
            op=MPI.SUM, root=0)
end = time.time()
if rank is 0:
    print ("I get for PI {0}". format(PI_ALL))
    print("I needed {0} seconds". format(end-start))
