c - 为什么执行此 C MPI 应用程序进行 Pi 近似时的结果总是相同?

标签 c parallel-processing mpi pi srand

这个用于 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/

相关文章:

python - 在 Sun Grid Engine 中运行 Python MPI 程序

c - 什么是适用于 OSX、Windows XP 或 DOS 的良好 C 编译器?

java - Java 8 的 forEachOrdered() 和 sequential() 方法之间的区别?

java - Java 中并行流的实用用例有哪些?

来自未知来源的 MPI 接收

c - 错误: expression must be a pointer to a complete object type

c - a1,a2...a10 等于每个元素并对元素进行计数

c - radiotimer_start() C 函数背后的逻辑是什么?

c - C 中的优化矩阵乘法

java - 并行写入 Ehcache 有危险吗?