首页 > 解决方案 > MPI、C - 无法正确生成随机数

问题描述

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

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

但是,当我运行我的代码时,我发现具有偶数等级的进程(例如等级 0 或等级 2 或等级 4)只分配了随机数 0。只有 0。
同时,具有奇数等级的进程(例如rank 1 或 rank 3 或 rank 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

谢谢

标签: cmpi

解决方案


核心问题是time(NULL)+world_rank

这些结合得好吗?


根据定义,所有偶数进程当然具有最低有效位world_rank0 和奇数位 1。

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

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

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


第一步是报告时间进程 ID

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

接下来某种+. 让我们散列world_rankt确保值不是无关紧要的。

示例:平凡的线性同余生成器

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

现在结合:

srand(t_hashed ^ world_rank);

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


推荐阅读