0
votes

The #pragma omp parallel for requires that the loop variable is an integer. So what happens if the loop variable is not an integer, as in this example?

    #include <stdio.h>
    #include <math.h>

    #define START (M_PI/2)
    #define END (M_PI*2)

    double f(double x)
    { return sin(x/2)+1;
    }

    int main(int argc, char *argv[])
    { double total = 0, x;
    int partitions;
    double slice;

    printf("How many partitions? "); fflush(stdout);
    scanf("%d", &partitions);
    slice = (END-START)/partitions;
    for (x = START + (slice/2); x < END; x = x + slice)
    total = total + f(x);
    total = total * slice;

    printf("The integration is %1.20f\n", total);
    }

How to convert this program into an OpenMP? Thanks

1
Why are you using slice for the loop counter rather than partitions?Andrew Fan
Actually I just start learning openMP and i found this question a challenge for me , if you run the above serial code it will run properly to compute the integration using the function f(x) = sin(x/2) +1 between Pi/2 and 2 Pi,Ahmed
so the problem is "#pragma omp parallel for" requires integer loop variable.. what if not integer ?Ahmed
Due to subtle rounding issues for (x = START + (slice/2); x < END; x = x + slice) may iterate +/- 1 more iterations than expected.chux - Reinstate Monica

1 Answers

1
votes

First, you should be a bit more careful with the style of your code, especially with the indentation. Code like

for (x = START + (slice/2); x < END; x = x + slice)
total = total + f(x);
total = total * slice;

can be quite misleading, and you make your life much easier when writing it as

for (x = START + (slice/2); x < END; x = x + slice) {
  total = total + f(x);
}
total = total * slice;

instead.

Regarding your problem, as mentioned by Andrew, you can avoid it altogether by looping over the partitions with an integer variable, i.e.,

#pragma omp parallel for private(x) reduction(+:total)
for(int i = 0; i < partitions; i++) {
  x = START + slice/2 + i*slice;
  total = total + f(x);
}
total = total * slice;