这个用于 Pi 近似的 C MPI 应用程序总是针对每个问题大小打印出相同的结果,即随机生成的点数 (npts
)。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "mpi.h"
int main(int argc, char *argv[]) {
int myid,nprocs;
double PI25DT = 3.141592653589793238462643;
long long npts = 1e10;
long i,mynpts;
long double f,sum,mysum;
long double xmin,xmax,x;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
if (myid == 0) {
mynpts = npts - (nprocs-1)*(npts/nprocs);
} else {
mynpts = npts/nprocs;
}
mysum = 0.0;
xmin = 0.0;
xmax = 1.0;
srand(myid);
for (i=0; i<mynpts; i++) {
x = (long double) rand()/RAND_MAX*(xmax-xmin) + xmin;
mysum += 4.0/(1.0 + x*x);
}
MPI_Reduce(&mysum,&sum,1,MPI_LONG_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
if (myid == 0) {
f = sum/npts;
printf("PI calculated with %lld points = %.16f \n",npts,f);
printf("Error is: %.16f \n",fabs(f-PI25DT));
}
MPI_Finalize();
}
这是输出。我认为每次运行应用程序的结果应该有所不同。我在具有 128 个节点的集群上执行它。
$ mpicc pi.c -o /mnt/cluster_128/pi
$ mpirun -np 128 --hostfile hosts_4cores_128.mpi /mnt/cluster_128/pi
PI calculated with 10000000000 points = 3.1415901444578158
Error is: 0.0000025091319773
$ mpirun -np 128 --hostfile hosts_4cores_128.mpi /mnt/cluster_128/pi
PI calculated with 10000000000 points = 3.1415901444578158
Error is: 0.0000025091319773
$ mpirun -np 128 --hostfile hosts_4cores_128.mpi /mnt/cluster_128/pi
PI calculated with 10000000000 points = 3.1415901444578158
Error is: 0.0000025091319773
$ mpirun -np 128 --hostfile hosts_4cores_128.mpi /mnt/cluster_128/pi
PI calculated with 10000000000 points = 3.1415901444578158
Error is: 0.0000025091319773
最佳答案
您正在此处播种 PRNG:
srand(myid);
myid
是通过调用 MPI_Comm_rank()
设置的值,您只对 myid == 0
的结果感兴趣,所以这总是相同的值。播种相同的值会产生相同的“随机”数字序列。
改用常见的播种习语:
#include <time.h>
#include <stdlib.h>
[...]
srand(time(0));
关于c - 为什么执行此 C MPI 应用程序进行 Pi 近似时的结果总是相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46971121/