#include <stdio.h>
#include "mpi.h"
#include <math.h>
#define PI acos(-1.0)
int main(int argc, char**argv){
int rank, size;
int n, i, start, end;
double sum, psum, total, rate;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(comm, &size);
MPI_Comm_rank(comm, &rank);
if (rank == 0){
printf("Input n:");
scanf("%d", &n);
for (i = 1; i < size; i++)
MPI_Send(&n, 1, MPI_INT, i, 99, comm);
}
else{
MPI_Recv(&n, 1, MPI_INT, 0, 99, comm, &status);
}
double h = 2 * PI / n;
start = n / size * rank +1;
end = n / size * (rank + 1);
sum = 0;
for (i = start; i <= end; i++){
rate = i*1.0 / n;
sum += cos(rate*2*PI + h/2) * h;
}
if (rank != 0)
MPI_Send(&sum, 1, MPI_DOUBLE, 0, 99, comm);
printf("part sum from %d to %d of process %d is %lf.\n", start, end, rank, sum);
if (rank == 0){
total = sum;
for (i = 1; i < size; i++){
MPI_Recv(&psum, 1, MPI_DOUBLE, i, 99, comm, &status);
total += psum;
}
printf("sum is %lf.\n", total);
}
MPI_Finalize();
return 0;
}