pi_mpi.c
954 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#include <string.h>
#include <mpi.h>
#define N 100000000
int main (int argc, char** argv)
{
int rank;
int size;
long long int n;
long long int i;
double l_sum,total_sum, x, h;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
n=N;
if(rank==0)
{
if(argc==2)
{
n = atol(argv[1]);
}
printf("MPI version with process = %d\n", size);
printf("Number of intervals: %lld\n", n);
}
MPI_Bcast(&n, 1, MPI_LONG, 0, MPI_COMM_WORLD);
h = 1.0/n;
l_sum = 0.0;
for (i = rank; i < n; i += size)
{
x = (i + 0.5)*h;
l_sum += 4.0/(1.0 + x*x);
}
l_sum *= h;
MPI_Reduce(&l_sum,&total_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
if(rank==0)
{
printf("Pi=%0.12g\n", total_sum);
}
MPI_Finalize();
return 0;
}