c - 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
谢谢
解决方案
核心问题是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);
接下来,以某种比+
. 让我们散列world_rank
或t
确保值不是无关紧要的。
示例:平凡的线性同余生成器
const unsigned m = 1664525u;
const unsigned c = 1013904223u;
unsigned t_hashed = (unsigned) t;
t_hashed = m*t_hashed + c;
现在结合:
srand(t_hashed ^ world_rank);
如果这不能提供令人满意的结果,则需要其他数字熵来源。
推荐阅读
- ffmpeg - ffmpeg不正确的屁股字幕边框宽度
- python-3.x - ImportError: DLL load failed: The specified module could not be found IOT Simulate
- java - Spring Service - 我应该传递实体 ID 还是实体本身?
- r - 有没有办法编写一个随机采样数据帧中连续行的单行命令?
- c++ - 程序运行两次后关闭
- vue.js - 如何以编程方式基于变量添加事件?
- turbo-c++ - 我正在尝试使用 System() 函数在 C 程序中打开记事本文件,我的代码在 Dev C++ 中工作,但在 turbo 中不工作
- ios - 为什么我的应用被拒绝原因“恢复购买”功能允许用户恢复以前购买的应用内购买
- javascript - 刷新页面删除引导选择样式
- mysql - VB.Net 无法识别活动的 MySQL 事务