C中的平行梯形规则

时间:2018-11-14 21:43:58

标签: c function pointers parallel-processing

我编写了一个程序,通过扩展梯形规则将给定积分作为函数进行计算。看来我陷入了无限循环,但我不明白为什么。我认为问题出在do_cmd函数中。或带有参考和指针的东西。请帮忙。我尝试实现收集的通信。 先感谢您。

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

int rank, size;

double part_of_integral(int n_start, int n_end, double a, double b, double h, double(*f)(double)){
    double temp = f(n_start * h + a) + f(n_end * h + a);
    temp *= h;
    temp /= 2.0;
    int i;
    for (i = n_start + 1; i < n_end; ++i) {
        temp += h * f(i * h);
    }
    return temp;
}
double func(double x){
    return 1.0 / (1.0 + pow(x, 2.0));
}

double do_cmd(double* a, double* b, int* n){
    MPI_Barrier(MPI_COMM_WORLD);
    printf("a = %f, b = %f, n = %d, rank = %d\n", *a, *b, *n, rank);
    MPI_Bcast(a, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(b, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(n, 1, MPI_INT, 0, MPI_COMM_WORLD);
    printf("aa= %f, bb = %f, nn = %d, rankb = %d\n", *a, *b, *n, rank);

    double h = (*b - *a) / *n;
    int number_of_nodes = *n / size;
    int n_start = rank * number_of_nodes;
    int n_end = (rank + 1) * number_of_nodes;
    double integral_output = part_of_integral(n_start, n_end, *a, *b, h, func);
    double integral_result = 0.0;
    MPI_Reduce(&integral_output, &integral_result, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
    if (rank == 0) {
        integral_result *= 4.0;
    }
    return integral_result;
}

int main (int argc, char* argv[]) {
    double a, b, tn, t2n;
    int n;
    double error = 1.0;
    const double min_error = 1.0e-8;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    tn = 0.0;
    if (rank == 0) {
            a = 0.0;
            b = 1.0;
            n = 2;  
        }
    while(error > min_error) {


        t2n = do_cmd(&a, &b, &n);
        error = fabs(((3.0/4.0) * t2n) - ((1.0/3.0) * tn));
        if (rank == 0) {
            printf ("error: %f\n", error);
            n *= 2;
        }
        t2n = tn;
    }
    if (rank == 0) {
        printf ("n = %d, 2n = %d, error = %f\n", n/2, n, error);
    }
    MPI_Finalize();
    return 0;
    }

0 个答案:

没有答案