0

The following C program calculate the value of PI using multiple threads.

#include <stdio.h>
#define N 10000000

int main(int argc, char **argv)
{
    long int i, n = N;
    double x, dx, f, sum, pi;
    printf("number of intervals: %ld\n", n);
    sum = 0.0;

    dx = 1.0/(double)n;
    #pragma omp parallel for private(x,f,i) shared(dx, sum,n)
    for (i = 1; i<=n; i++){
        x = dx*((double)(i-0.5));
        f = 4.0/(1.0+x*x);
        #pragma omp critical
        sum+=f;
    }

    pi = dx*sum;

    printf("PI %.24f\n", pi);

    return 0;
}

As far as I can see, the only shared variable on which race condition can occur is "sum", which in fact is executed using the Critical clause. However, every time I get different results:

number of intervals: 10000000
PI 3.141592653589736272579103

number of intervals: 10000000
PI 3.141592653589804218228210

number of intervals: 10000000
PI 3.141592653589829975402381

If run the same code but using Reduction instead of Critical I get every time the same result:

number of intervals: 10000000
PI 3.141592653589669659197625

What am I doing wrong?

DevXino
  • 1
  • 1
  • `double` values only have precision for about 15 decimal digits. You printing 24 decimal digits doesn't make it more precise. There's also no need for any of the casts you have. – Some programmer dude May 11 '22 at 11:11
  • 3
    Floating point arithmetic is not associative, i.e. `(a + b) + c` is generally not the same as `a + (b + c)`. The difference will be minimal (i.e. both results will be fine for most purposes), but visible. As the order of the summation in parallel is random, you will get slightly different results with each run. – paleonix May 11 '22 at 11:39
  • 2
    For performance use a `reduce` clause instead of critical region, i.e. `reduce(+: sum)` as part of the pragma in front of the loop. – paleonix May 11 '22 at 11:42
  • 1
    Does this answer your question? [Summing up array elements using OpenMP is not working correctly for large arrays (C)](https://stackoverflow.com/questions/39611779/summing-up-array-elements-using-openmp-is-not-working-correctly-for-large-arrays) – paleonix May 11 '22 at 11:44

0 Answers0