double integrate(double x_min, double x_max, double step, std::function<double(double)> func) {
double retval = 0;
double half_step = step / 2.0;
for (double x = x_min; x + step <= x_max; x += step) {
double x1 = x;
double x2 = std::min(x + step, x_max);
// std::cout << "Mnoze " << x1 << " z " << x2 << " oraz licze " << licznik++ << std::endl;
retval += (func(x1) + func(x2)) * half_step;
}
return retval;
}
#pragma omp critical
,但我不知道放在哪里。
double integrate_omp(double x_min, double x_max, double step, std::function<double(double)> func) {
double retval = 0;
double half_step = step / 2.0;
int numOfIt = std::ceil((x_max - x_min) / step);
int i;
double x1, x2;
double sum = 0;
#pragma omp parallel for private(i)
for (i = 0; i < numOfIt; i++)
{
x1 = x_min + i * step;
x2 = std::min(x_min + step + i * step, x_max);
retval+= (func(x1) + func(x2)) * half_step;
}
return retval;
}
好吧,我明白了。我做了一些修改,现在我的代码给了我正确的答案,看起来像:
double integrate_omp(double x_min, double x_max, double step, std::function<double(double)> func) {
double retval=0;
double half_step = step / 2.0;
int numOfIt = std::ceil((x_max - x_min) / step);
int i;
double sum = 0;
#pragma omp parallel for private(i)
for (i = 0; i < numOfIt; i++)
{
double x1 = x_min + i * step;
double x2 = std::min(x_min + step + i * step, x_max);
#pragma omp critical
retval=retval + ((func(x1) + func(x2)) * half_step);
}
return retval;
}
但使用:
#pragma omp critical
在那没有意义,甚至没有使用过omp。
我应该怎么做才能使其正常工作?