MPI,C-无法正确生成随机数

时间:2018-10-03 01:35:06

标签: c mpi

嗨,我是Stackoverflow的新手。
我在C中使用MPI。我正在运行10个进程。

我的每个进程都包含一个随机数生成器,该生成器唯一地为该进程生成一个随机数(0或1)。

但是,当我运行代码时,我发现具有偶数等级的进程(例如等级0或等级2或等级4)仅分配给随机数0。仅分配给0。
同时,仅对具有奇数编号等级(例如等级1或等级3或等级4)的进程分配随机数1。

如何修改我的代码,以使某些偶数个进程可以分配随机数1,而某些奇数个进程可以分配随机数0?

这是我的代码:

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

int main(int argc, char** argv) {
    // Initialize the MPI environment
    MPI_Init(NULL, NULL);

    // Get the number of processes
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);

    // Get the rank of the process
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

    //try to generate unique random number 
    srand(time(NULL)+world_rank);
    int rando =  rand()%2;
    // Print off rank with random number
    printf("Rank %d has the random value %d\n", world_rank, rando);

    // Finalize the MPI environment.
    MPI_Finalize();
}

这是我的输出:

Rank 0 has the random value 0
Rank 7 has the random value 1
Rank 8 has the random value 0
Rank 9 has the random value 1
Rank 1 has the random value 1
Rank 2 has the random value 0
Rank 4 has the random value 0
Rank 3 has the random value 1
Rank 5 has the random value 1
Rank 6 has the random value 0

谢谢

1 个答案:

答案 0 :(得分:0)

核心问题是time(NULL)+world_rank

这些组合在一起好吗?


根据定义,所有偶数过程的world_rank最低有效位当然为0,奇数为1。

对于一天中的给定时间(以秒为单位),如果大约在同一时间启动,则time()中的值对于该过程的每个开始可能是相同的。

我们可以合理确定time()的属性:它会增加,每秒相同。

我们不知道进程标识符独立于时间


第一步是报告时间进程ID

time_t t = time(NULL);
printf("time() %lld\n", (long long) t);
printf("process %d\n", world_rank);

接下来,以某种比+更好的方式组合时间进程ID 。让我们对world_rankt进行哈希处理,以确保值之间的关系不大。

示例:琐碎的Linear congruential generator

const unsigned m = 1664525u;
const unsigned c = 1013904223u;
unsigned t_hashed = (unsigned) t;
t_hashed = m*t_hashed + c;

现在结合:

srand(t_hashed ^ world_rank);

如果不能提供令人满意的结果,则需要数字entropy的其他来源。

相关问题