Skip to content
Snippets Groups Projects
pi3halfdone.c 1.41 KiB
Newer Older
  • Learn to ignore specific revisions
  • jansik's avatar
    jansik committed
    #include "mpi.h"
    #include <math.h>
    #include <stdio.h>
    #include <omp.h>
     
    int main(argc,argv)
    int argc;
    char *argv[];
    {
        int done = 0, n, myid, numprocs, i, len, provided, tid;
        double PI25DT = 3.141592653589793238462643;
        double mypi, pi, h, sum, x;
        char   pname[MPI_MAX_PROCESSOR_NAME];
         
        MPI_Init_thread(&argc,&argv,MPI_THREAD_FUNNELED,&provided);
        if (provided<MPI_THREAD_FUNNELED) 
        { MPI_Finalize(); return 1; }
    
        MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
        MPI_Comm_rank(MPI_COMM_WORLD,&myid);
    
        MPI_Get_processor_name(pname,&len); 
        printf("Process %d of %d is alive on host %s\n",myid,numprocs,pname);
    
    
        while (!done)
        {
            if (myid == 0) {
                printf("Enter the number of intervals: (0 quits) ");
                scanf("%d",&n);
            }
            //Work: Broadcast n to all ranks
            if (n == 0) break;
             
            h   = 1.0 / (double) n;
            sum = 0.0;
    
            //Work: Split the loop over MPI processes
            for (i = 1; i <= n; i ++) {
                //Work: Find out which process runs which iterations
                x = h * ((double)i - 0.5);
                sum += 4.0 / (1.0 + x*x);
            }
            mypi = h * sum;
            
            //Work: Do reduction of partial results into pi 
             
            if (myid == 0)
                printf("pi is approximately %.16f, Error is %.16f\n",
                       pi, fabs(pi - PI25DT));
        }
        MPI_Finalize();
        return 0;
    }