cloopsopenmpreduction

Why do I get the wrong results while calculating the mean of the array using openMP?


#include <stdio.h>
#include <omp.h>

#define N 5

int X[N];

int main() {
    int num = 0;
    int moy = 0;

    // Initialize the array (you should populate it as needed)
    for (int i = 0; i < N; i++) {
        X[i] = i * 2; // Example initialization
    }

    // Calculate the average
    #pragma omp parallel for reduction(+:moy)
    for (int i = 0; i < N; i++) {
        moy += X[i] / N;
    }

    // Count elements greater than the average
    #pragma omp parallel for reduction(+:num)
    for (int i = 0; i < N; i++) {
        if (X[i] > moy) {
            num++;
        }
    }

    printf("%d\n", num);

    return 0;
}

If I write the print statements for mean, num and elements of the array I get the following output:
Average (moy): 2
Elements in X: 0 2 4 6 8
Number of elements greater than the average: 3


Solution

  • This is not an openmp problem , you declared moy as an int and then to calculate the mean you do:

    moy += X[i] / N;

    your X array contains 0, 2, 4, 6, 8 and N = 5, when the division is performed you are trying to put a double inside an int so your sum becomes essentially:

    0/5 = 0 + 2/5 = 0 + 4/5 = 0 + 6/5 = 1 + 8/5 = 1 = 0+0+0+1+1 = 2

    you need to either make moy and X a double or, better, to make moy a double, sum all the elements inside moy AND THEN do moy/N to get the correct result