Calculating PI with openmp

Viewed 57

Good morning everyone,

I am trying to calculate pi and compare two results of the following two approachs. My problem is : in the 2nd approach, in the loop, when i printf("%d",thid); i get the same result as the 1st approach. But when I remove it, I get a totally random result.

Can someone help me understand where I went wrong ?

#include <chrono>
#include <iostream>
#include <omp.h>

inline double f(double x)
{
  return (4 / (1 + x * x));
}

int main()
{
    int i;
    const int N = 100000;
    double pi = 0.0;
    omp_set_num_threads(8);

    
    start = std::chrono::high_resolution_clock::now();

    #pragma omp parallel
    {
        #pragma omp for reduction(+:pi)
            for (int i=0; i<N; i++)
            {
                pi+=((f(i/N)+f((i+1)/N))/2*N);
            }
    }
    std::cout << "pi = " << pi << std::endl;
    std::chrono::duration<double> tempsOmpFor = std::chrono::high_resolution_clock::now() - start;
    std::cout << "Temps parallel omp for: " << tempsOmpFor.count() << "s\n";

//2nd approach

    pi = 0.0;
    double pii = 0.0;
    start = std::chrono::high_resolution_clock::now();
    #pragma omp parallel
    {   
        int thid = omp_get_thread_num();
        int thread_numbers = omp_get_num_threads();
        
        for (int i=((thid * N)/thread_numbers); i<(((thid + 1) * N)/thread_numbers); i++)
        {
            pi+=((f(i/N)+f((i+1)/N))/2*N);
            printf("%d",thid);
        }

        #pragma omp critical
                pi+=pii;
                
    }
    std::cout << "pi = " << pi << std::endl;
    std::chrono::duration<double> tempsForMain = std::chrono::high_resolution_clock::now() - start;
    std::cout << "Temps parallel for a la main: " << tempsForMain.count() << "s\n"; 
  
return 0;
}
1 Answers

I managed to solve it : I added the critical section before the sum of pi.

for (int i=((thid * N)/thread_numbers); i<(((thid + 1) * N)/thread_numbers); i++)
        {
            #pragma omp critical
            pi+=((f(i/N)+f((i+1)/N))/2*N);
        }

And I deleted the pii parts.

Thanks to the people who answered and helped.

Related