Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ============================================================================
- Name : Laborator1.c
- Author :
- Version :
- Copyright : Your copyright notice
- Description : Calculate Pi in MPI
- ============================================================================
- */
- #include <mpi.h>
- #include <stdio.h>
- #include <string.h>
- void
- calc_pi(int rank, int num_procs)
- {
- int i;
- int num_intervals;
- double h;
- double mypi;
- double pi;
- double sum;
- double x;
- /* set number of intervals to calculate */
- if (rank == 0) {
- num_intervals = 100000000;
- }
- /* tell other tasks how many intervals */
- MPI_Bcast(&num_intervals, 1, MPI_INT, 0, MPI_COMM_WORLD);
- /* now everyone does their calculation */
- h = 1.0 / (double) num_intervals;
- sum = 0.0;
- for (i = rank + 1; i <= num_intervals; i += num_procs) {
- x = h * ((double)i - 0.5);
- sum += (4.0 / (1.0 + x*x));
- }
- mypi = h * sum;
- /* combine everyone's calculations */
- MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
- if (rank == 0) {
- printf("PI is approximately %.16f\n", pi);
- }
- }
- int
- main(int argc, char *argv[])
- {
- int my_rank; /* rank of process */
- int n; /* number of processes */
- int source; /* rank of sender */
- int dest = 0; /* rank of receiver */
- int tag = 0; /* tag for messages */
- char message[100]; /* storage for message */
- MPI_Status status ; /* return status for receive */
- int m = 3;
- int s = 0;
- int A[8] = {3,7,15,19,30,4,1,72};
- int mask = 0;
- int i = 0;
- int sr;
- s = A[my_rank];
- mask = 0;
- /* start up MPI */
- MPI_Init(&argc, &argv);
- /* find out process rank */
- MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
- /* find out number of processes */
- MPI_Comm_size(MPI_COMM_WORLD, &n);
- for (i= 0; i<m-1; i++)
- {
- if (my_rank && mask == 0)
- {
- if (my_rank && 2<<i == 0)
- {
- source = my_rank^ 2<<i;
- //receive sr from source
- MPI_Recv(sr, 1, MPI_INT, source, tag,MPI_COMM_WORLD,&status);
- printf("%d <= \"%d\"\n",my_rank, sr);
- s = s + sr;
- }
- else
- {
- dest = my_rank^ 2<<i ;
- //send s to destination
- MPI_Send(s,1, MPI_INT,dest, tag, MPI_COMM_WORLD);
- printf("%d => \"%d\"\n",my_rank,s);
- }
- }
- //mask ← mask xor 2i
- mask = mask^2<<i;
- }
- printf("sum is = %d",s);
- /* calculate PI */
- calc_pi(my_rank, n);
- /* shut down MPI */
- MPI_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement