-1

So I have a question regarding my little MPI program. (I am new to programming so its probably just some beginners mistake)

I made a program which calculates pi by using the formula: (1/n) * the sum of 4/(1+(i/n)^2);

Only problem is, I have to define the number of iterations in the root function, but as soon as I set any kind of braces around it the program doesn't work anymore. Is there any way to define "n" outside of root but give it a value inside of the root function? Or is it just some braces problem and if I set them correctly it will still work fine.

Thanks in advance

Code: (Problem starts at "if(process_rank == ROOT)" - yes there are no braces right now)

#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h>
#include <mpi.h>
#include <math.h>

#define ROOT 0

void print_time(double time)
{
    printf("TIME:%.10f\n", time * 1000.0); // Print execution time in ms    
}

int main(int argc, char *argv[])
{
    int communicator_size, process_rank; //n
    double pi_appr; //time_elapsed
    double PI_ORIGINAL = 3.141592653589793238462643; // Original pi value for comparison

    double i, n; //size, error, rank
    double result=0.0, sum=0.0, begin=0.0, end=0.0; //pi=0.0

    MPI_Init(&argc, &argv); //error=
    MPI_Comm_size(MPI_COMM_WORLD, &communicator_size); //
    MPI_Comm_rank(MPI_COMM_WORLD, &process_rank); //&process_rank

    //Synchronize all processes and get the begin time
    MPI_Barrier(MPI_COMM_WORLD);
    begin = MPI_Wtime();

    if(process_rank == ROOT)
        
        n = 1000000; // Root defines number of computation iterations 
    

    n = 1000000; //if i dont declare n here again it doesnt work

    //Each process will caculate a part of the sum
    for (i=process_rank; i<n; i+=communicator_size) 
    {
        result += 4/(1+((i/n)*(i/n))); // for some reason pow() didnt work
    }

    //now we some up the results with MPI_Reduce
    MPI_Reduce(&result, &sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
    
    //Synchronize all processes and get the end time
    MPI_Barrier(MPI_COMM_WORLD);
    end = MPI_Wtime();

    if (process_rank == ROOT)
    {
        pi_appr = (1/n)*sum; //calculate 

        printf("%f\n", end-begin); //we print the time by substracting the begin- from the end-time
        printf("Computed pi: %.16f (Error = %.16f)\n", pi_appr, fabs(pi_appr - PI_ORIGINAL));
    }

    MPI_Finalize();

    return 0;
}
IDS
  • 1
  • 1

1 Answers1

2

You are misunderstanding how MPI works. It has independent processes and distributed memory. So if you initialize a variable only in one process, it will not be initialized in other processes. You could use a MPI_Bcast call to communicate a value from the root to other processes.

Victor Eijkhout
  • 5,088
  • 2
  • 22
  • 23
  • Ofc I have to do a broadcast so every node knows what n is. Thank you for your help so far I will implement it as soon as I get home. – IDS May 21 '22 at 07:53