跟随MPI程序通过矩形计算曲线下面积的误差是什么?区域总和法

时间:2017-04-27 04:32:39

标签: c mpi

我通过在0到1的范围内找到曲线4/1 +(x * x)下面积来计算pi(3.14)的值。以下是C中的MPI程序。

但是,当有一个进程时,它会给出正确的值。如果我给出多个进程,则只有具有等级0的进程给出一些值,而其他进程给出0.0作为其本地计算值

以下代码中有什么错误?

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

#define MAX_NAME 80 
int main(int argc,char *argv[])
{


    MPI_INIT(&argc,&argv);
    int rank,nprocs,len;
    double i=0.0;
    double n=1000000000.0;
    double PI25DT =3.141592653589793238462643;
    double mypi,pi,step,sum,x;
    char name[MAX_NAME];
    double start_time,end_time,computation_time;
    MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
   MPI_Comm_rank(MPI_COMM_WORLD,&rank);
   MPI_Get_processor_name(name,&len);   
   start_time=MPI_Wtime();

    sum=0.0;
    step=1.0/(double)n;

    x=0.0;
    x=(double)rank*(n/nprocs);
    x=x+step;
    double temp=x;
    for(i=temp;i<(temp+(n/nprocs));i=i+1.0)
    {

       sum+=step*(4.0/(1.0+(double)(x*x)));
       x=x+step;    
     }


    mypi=sum;
    printf("\nProcessor: %d Name: %s Sum: %.16f \n",rank,name,mypi);
    MPI_Barrier(MPI_COMM_WORLD);
    MPI_Reduce(&mypi,&pi,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);

    if(rank==0)
    {
    printf("\nValue of Pi is %.16f approximately .Error is %.16f \n",pi,fabs(pi-PI25DT));
    end_time=MPI_Wtime();
    computation_time=end_time-start_time;
    printf("\nComputation time is: %f seconds.\n",computation_time);
    }
   MPI_Finalize();
  }

为一个流程和多个流程输出上述代码如下:

OUTPUT

1 个答案:

答案 0 :(得分:0)

代码中的整个逻辑似乎有缺陷 - 你在“for”循环中混淆了整数和双精度,这意味着循环限制都是错误的。

调试简单程序的最简单方法就是打印到屏幕上 - 我总是惊讶于那些沉默寡言的人只是让他们的程序告诉他们实际上在做什么。

如果我设置n = 5.0并将循环更改为:

x=x+step;
printf("rank %d has x = %lf\n", rank, x);

然后我得到2个进程:

rank 0 has x = 0.400000
rank 0 has x = 0.600000
rank 0 has x = 0.800000

Processor: 0 Name: starless Sum: 2.0471212357622095 

Value of Pi is 2.3040395511642187 approximately .Error is 0.8375531024255745 

Computation time is: 0.000067 seconds.
rank 1 has x = 2.900000
rank 1 has x = 3.100000
rank 1 has x = 3.300000

Processor: 1 Name: starless Sum: 0.2569183154020093 

显示循环限制是错误的。

我不认为他们在一个过程中甚至是正确的:

rank 0 has x = 0.400000
rank 0 has x = 0.600000
rank 0 has x = 0.800000
rank 0 has x = 1.000000
rank 0 has x = 1.200000

当然积分在0.0到1.0之间

此致

大卫